From b2057f506a09e2adef81fc77efd697d16ae14bec Mon Sep 17 00:00:00 2001 From: bernard Date: Thu, 2 Nov 2017 13:50:42 +0800 Subject: [External] Remove external from RT-Thread --- .../external/SQLite-3.8.1/tool/build-all-msvc.bat | 529 --- .../external/SQLite-3.8.1/tool/build-shell.sh | 22 - .../external/SQLite-3.8.1/tool/checkSpacing.c | 84 - components/external/SQLite-3.8.1/tool/diffdb.c | 44 - components/external/SQLite-3.8.1/tool/extract.c | 46 - .../external/SQLite-3.8.1/tool/fast_vacuum.c | 234 - components/external/SQLite-3.8.1/tool/fragck.tcl | 149 - .../external/SQLite-3.8.1/tool/genfkey.README | 137 - components/external/SQLite-3.8.1/tool/genfkey.test | 354 -- components/external/SQLite-3.8.1/tool/getlock.c | 134 - components/external/SQLite-3.8.1/tool/lemon.c | 4897 -------------------- components/external/SQLite-3.8.1/tool/lempar.c | 850 ---- components/external/SQLite-3.8.1/tool/logest.c | 141 - .../external/SQLite-3.8.1/tool/mkautoconfamal.sh | 83 - .../external/SQLite-3.8.1/tool/mkkeywordhash.c | 602 --- components/external/SQLite-3.8.1/tool/mkopts.tcl | 51 - .../external/SQLite-3.8.1/tool/mkpragmatab.tcl | 393 -- .../external/SQLite-3.8.1/tool/mkspeedsql.tcl | 237 - .../SQLite-3.8.1/tool/mksqlite3c-noext.tcl | 305 -- .../external/SQLite-3.8.1/tool/mksqlite3c.tcl | 334 -- .../external/SQLite-3.8.1/tool/mksqlite3h.tcl | 111 - .../SQLite-3.8.1/tool/mksqlite3internalh.tcl | 145 - components/external/SQLite-3.8.1/tool/mkvsix.tcl | 655 --- components/external/SQLite-3.8.1/tool/offsets.c | 329 -- components/external/SQLite-3.8.1/tool/omittest.tcl | 298 -- .../external/SQLite-3.8.1/tool/opcodeDoc.awk | 23 - components/external/SQLite-3.8.1/tool/pagesig.c | 92 - .../external/SQLite-3.8.1/tool/restore_jrnl.tcl | 233 - .../external/SQLite-3.8.1/tool/rollback-test.c | 155 - components/external/SQLite-3.8.1/tool/showdb.c | 864 ---- .../external/SQLite-3.8.1/tool/showjournal.c | 139 - components/external/SQLite-3.8.1/tool/showwal.c | 590 --- components/external/SQLite-3.8.1/tool/soak1.tcl | 103 - .../external/SQLite-3.8.1/tool/space_used.tcl | 111 - .../external/SQLite-3.8.1/tool/spaceanal.tcl | 781 ---- .../external/SQLite-3.8.1/tool/speedtest.tcl | 275 -- .../external/SQLite-3.8.1/tool/speedtest16.c | 169 - .../external/SQLite-3.8.1/tool/speedtest2.tcl | 207 - components/external/SQLite-3.8.1/tool/speedtest8.c | 260 -- .../external/SQLite-3.8.1/tool/speedtest8inst1.c | 216 - .../external/SQLite-3.8.1/tool/split-sqlite3c.tcl | 82 - .../external/SQLite-3.8.1/tool/stack_usage.tcl | 98 - .../external/SQLite-3.8.1/tool/symbols-mingw.sh | 33 - components/external/SQLite-3.8.1/tool/symbols.sh | 34 - components/external/SQLite-3.8.1/tool/tostr.awk | 8 - .../external/SQLite-3.8.1/tool/vdbe-compress.tcl | 128 - .../external/SQLite-3.8.1/tool/warnings-clang.sh | 14 - components/external/SQLite-3.8.1/tool/warnings.sh | 19 - .../external/SQLite-3.8.1/tool/win/sqlite.vsix | Bin 32825 -> 0 bytes 49 files changed, 15798 deletions(-) delete mode 100644 components/external/SQLite-3.8.1/tool/build-all-msvc.bat delete mode 100644 components/external/SQLite-3.8.1/tool/build-shell.sh delete mode 100644 components/external/SQLite-3.8.1/tool/checkSpacing.c delete mode 100644 components/external/SQLite-3.8.1/tool/diffdb.c delete mode 100644 components/external/SQLite-3.8.1/tool/extract.c delete mode 100644 components/external/SQLite-3.8.1/tool/fast_vacuum.c delete mode 100644 components/external/SQLite-3.8.1/tool/fragck.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/genfkey.README delete mode 100644 components/external/SQLite-3.8.1/tool/genfkey.test delete mode 100644 components/external/SQLite-3.8.1/tool/getlock.c delete mode 100644 components/external/SQLite-3.8.1/tool/lemon.c delete mode 100644 components/external/SQLite-3.8.1/tool/lempar.c delete mode 100644 components/external/SQLite-3.8.1/tool/logest.c delete mode 100644 components/external/SQLite-3.8.1/tool/mkautoconfamal.sh delete mode 100644 components/external/SQLite-3.8.1/tool/mkkeywordhash.c delete mode 100644 components/external/SQLite-3.8.1/tool/mkopts.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/mkpragmatab.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/mkspeedsql.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/mksqlite3c-noext.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/mksqlite3c.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/mksqlite3h.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/mksqlite3internalh.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/mkvsix.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/offsets.c delete mode 100644 components/external/SQLite-3.8.1/tool/omittest.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/opcodeDoc.awk delete mode 100644 components/external/SQLite-3.8.1/tool/pagesig.c delete mode 100644 components/external/SQLite-3.8.1/tool/restore_jrnl.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/rollback-test.c delete mode 100644 components/external/SQLite-3.8.1/tool/showdb.c delete mode 100644 components/external/SQLite-3.8.1/tool/showjournal.c delete mode 100644 components/external/SQLite-3.8.1/tool/showwal.c delete mode 100644 components/external/SQLite-3.8.1/tool/soak1.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/space_used.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/spaceanal.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/speedtest.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/speedtest16.c delete mode 100644 components/external/SQLite-3.8.1/tool/speedtest2.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/speedtest8.c delete mode 100644 components/external/SQLite-3.8.1/tool/speedtest8inst1.c delete mode 100644 components/external/SQLite-3.8.1/tool/split-sqlite3c.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/stack_usage.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/symbols-mingw.sh delete mode 100644 components/external/SQLite-3.8.1/tool/symbols.sh delete mode 100644 components/external/SQLite-3.8.1/tool/tostr.awk delete mode 100644 components/external/SQLite-3.8.1/tool/vdbe-compress.tcl delete mode 100644 components/external/SQLite-3.8.1/tool/warnings-clang.sh delete mode 100644 components/external/SQLite-3.8.1/tool/warnings.sh delete mode 100644 components/external/SQLite-3.8.1/tool/win/sqlite.vsix (limited to 'components/external/SQLite-3.8.1/tool') diff --git a/components/external/SQLite-3.8.1/tool/build-all-msvc.bat b/components/external/SQLite-3.8.1/tool/build-all-msvc.bat deleted file mode 100644 index ed05f959fe..0000000000 --- a/components/external/SQLite-3.8.1/tool/build-all-msvc.bat +++ /dev/null @@ -1,529 +0,0 @@ -@ECHO OFF - -:: -:: build-all-msvc.bat -- -:: -:: Multi-Platform Build Tool for MSVC -:: - -REM -REM This batch script is used to build the SQLite DLL for multiple platforms -REM and configurations using MSVC. The built SQLite DLLs, their associated -REM import libraries, and optionally their symbols files, are placed within -REM the directory specified on the command line, in sub-directories named for -REM their respective platforms and configurations. This batch script must be -REM run from inside a Visual Studio Command Prompt for the desired version of -REM Visual Studio ^(the initial platform configured for the command prompt does -REM not really matter^). Exactly one command line argument is required, the -REM name of an existing directory to be used as the final destination directory -REM for the generated output files, which will be placed in sub-directories -REM created therein. Ideally, the directory specified should be empty. -REM -REM Example: -REM -REM CD /D C:\dev\sqlite\core -REM tool\build-all-msvc.bat C:\Temp -REM -REM In the example above, "C:\dev\sqlite\core" represents the root of the -REM source tree for SQLite and "C:\Temp" represents the final destination -REM directory for the generated output files. -REM -REM There are several environment variables that may be set to modify the -REM behavior of this batch script and its associated Makefile. The list of -REM platforms to build may be overriden by using the PLATFORMS environment -REM variable, which should contain a list of platforms ^(e.g. x86 x86_amd64 -REM x86_arm^). All platforms must be supported by the version of Visual Studio -REM being used. The list of configurations to build may be overridden by -REM setting the CONFIGURATIONS environment variable, which should contain a -REM list of configurations to build ^(e.g. Debug Retail^). Neither of these -REM variable values may contain any double quotes, surrounding or embedded. -REM Finally, the NCRTLIBPATH and NSDKLIBPATH environment variables may be set -REM to specify the location of the CRT and SDK, respectively, needed to compile -REM executables native to the architecture of the build machine during any -REM cross-compilation that may be necessary, depending on the platforms to be -REM built. These values in these two variables should be surrounded by double -REM quotes if they contain spaces. -REM -REM Please note that the SQLite build process performed by the Makefile -REM associated with this batch script requires both Gawk ^(gawk.exe^) and Tcl -REM 8.5 ^(tclsh85.exe^) to be present in a directory contained in the PATH -REM environment variable unless a pre-existing amalgamation file is used. -REM -SETLOCAL - -REM SET __ECHO=ECHO -REM SET __ECHO2=ECHO -REM SET __ECHO3=ECHO -IF NOT DEFINED _AECHO (SET _AECHO=REM) -IF NOT DEFINED _CECHO (SET _CECHO=REM) -IF NOT DEFINED _VECHO (SET _VECHO=REM) - -%_AECHO% Running %0 %* - -REM SET DFLAGS=/L - -%_VECHO% DFlags = '%DFLAGS%' - -SET FFLAGS=/V /F /G /H /I /R /Y /Z - -%_VECHO% FFlags = '%FFLAGS%' - -SET ROOT=%~dp0\.. -SET ROOT=%ROOT:\\=\% - -%_VECHO% Root = '%ROOT%' - -REM -REM NOTE: The first and only argument to this batch file should be the output -REM directory where the platform-specific binary directories should be -REM created. -REM -SET BINARYDIRECTORY=%1 - -IF NOT DEFINED BINARYDIRECTORY ( - GOTO usage -) - -%_VECHO% BinaryDirectory = '%BINARYDIRECTORY%' - -SET DUMMY=%2 - -IF DEFINED DUMMY ( - GOTO usage -) - -REM -REM NOTE: From this point, we need a clean error level. Reset it now. -REM -CALL :fn_ResetErrorLevel - -REM -REM NOTE: Change the current directory to the root of the source tree, saving -REM the current directory on the directory stack. -REM -%__ECHO2% PUSHD "%ROOT%" - -IF ERRORLEVEL 1 ( - ECHO Could not change directory to "%ROOT%". - GOTO errors -) - -REM -REM NOTE: This batch file requires the ComSpec environment variable to be set, -REM typically to something like "C:\Windows\System32\cmd.exe". -REM -IF NOT DEFINED ComSpec ( - ECHO The ComSpec environment variable must be defined. - GOTO errors -) - -REM -REM NOTE: This batch file requires the VcInstallDir environment variable to be -REM set. Tyipcally, this means this batch file needs to be run from an -REM MSVC command prompt. -REM -IF NOT DEFINED VCINSTALLDIR ( - ECHO The VCINSTALLDIR environment variable must be defined. - GOTO errors -) - -REM -REM NOTE: If the list of platforms is not already set, use the default list. -REM -IF NOT DEFINED PLATFORMS ( - SET PLATFORMS=x86 x86_amd64 x86_arm -) - -%_VECHO% Platforms = '%PLATFORMS%' - -REM -REM NOTE: If the list of configurations is not already set, use the default -REM list. -REM -IF NOT DEFINED CONFIGURATIONS ( - SET CONFIGURATIONS=Debug Retail -) - -%_VECHO% Configurations = '%CONFIGURATIONS%' - -REM -REM NOTE: Setup environment variables to translate between the MSVC platform -REM names and the names to be used for the platform-specific binary -REM directories. -REM -SET amd64_NAME=x64 -SET arm_NAME=ARM -SET x64_NAME=x64 -SET x86_NAME=x86 -SET x86_amd64_NAME=x64 -SET x86_arm_NAME=ARM -SET x86_x64_NAME=x64 - -%_VECHO% amd64_Name = '%amd64_NAME%' -%_VECHO% arm_Name = '%arm_NAME%' -%_VECHO% x64_Name = '%x64_NAME%' -%_VECHO% x86_Name = '%x86_NAME%' -%_VECHO% x86_amd64_Name = '%x86_amd64_NAME%' -%_VECHO% x86_arm_Name = '%x86_arm_NAME%' -%_VECHO% x86_x64_Name = '%x86_x64_NAME%' - -REM -REM NOTE: Check for the external tools needed during the build process ^(i.e. -REM those that do not get compiled as part of the build process itself^) -REM along the PATH. -REM -FOR %%T IN (gawk.exe tclsh85.exe) DO ( - SET %%T_PATH=%%~dp$PATH:T -) - -REM -REM NOTE: The Gawk executable "gawk.exe" is required during the SQLite build -REM process unless a pre-existing amalgamation file is used. -REM -IF NOT DEFINED gawk.exe_PATH ( - ECHO The Gawk executable "gawk.exe" is required to be in the PATH. - GOTO errors -) - -REM -REM NOTE: The Tcl 8.5 executable "tclsh85.exe" is required during the SQLite -REM build process unless a pre-existing amalgamation file is used. -REM -IF NOT DEFINED tclsh85.exe_PATH ( - ECHO The Tcl 8.5 executable "tclsh85.exe" is required to be in the PATH. - GOTO errors -) - -REM -REM NOTE: Set the TOOLPATH variable to contain all the directories where the -REM external tools were found in the search above. -REM -SET TOOLPATH=%gawk.exe_PATH%;%tclsh85.exe_PATH% - -%_VECHO% ToolPath = '%TOOLPATH%' - -REM -REM NOTE: Check for MSVC 2012/2013 because the Windows SDK directory handling -REM is slightly different for those versions. -REM -IF "%VisualStudioVersion%" == "11.0" ( - REM - REM NOTE: If the Windows SDK library path has already been set, do not set - REM it to something else later on. - REM - IF NOT DEFINED NSDKLIBPATH ( - SET SET_NSDKLIBPATH=1 - ) -) ELSE IF "%VisualStudioVersion%" == "12.0" ( - REM - REM NOTE: If the Windows SDK library path has already been set, do not set - REM it to something else later on. - REM - IF NOT DEFINED NSDKLIBPATH ( - SET SET_NSDKLIBPATH=1 - ) -) ELSE ( - CALL :fn_UnsetVariable SET_NSDKLIBPATH -) - -REM -REM NOTE: Check if this is the Windows Phone SDK. If so, a different batch -REM file is necessary to setup the build environment. Since the variable -REM values involved here may contain parenthesis, using GOTO instead of -REM an IF block is required. -REM -IF DEFINED WindowsPhoneKitDir GOTO set_vcvarsall_phone -SET VCVARSALL=%VCINSTALLDIR%\vcvarsall.bat -GOTO set_vcvarsall_done -:set_vcvarsall_phone -SET VCVARSALL=%VCINSTALLDIR%\WPSDK\WP80\vcvarsphoneall.bat -:set_vcvarsall_done - -REM -REM NOTE: This is the outer loop. There should be exactly one iteration per -REM platform. -REM -FOR %%P IN (%PLATFORMS%) DO ( - REM - REM NOTE: Using the MSVC platform name, lookup the simpler platform name to - REM be used for the name of the platform-specific binary directory via - REM the environment variables setup earlier. - REM - CALL :fn_CopyVariable %%P_NAME PLATFORMNAME - - REM - REM NOTE: This is the inner loop. There should be exactly one iteration. - REM This loop is necessary because the PlatformName environment - REM variable was set above and that value is needed by some of the - REM commands contained in the inner loop. If these commands were - REM directly contained in the outer loop, the PlatformName environment - REM variable would be stuck with its initial empty value instead. - REM - FOR /F "tokens=2* delims==" %%D IN ('SET PLATFORMNAME') DO ( - REM - REM NOTE: Attempt to clean the environment of all variables used by MSVC - REM and/or Visual Studio. This block may need to be updated in the - REM future to account for additional environment variables. - REM - CALL :fn_UnsetVariable DevEnvDir - CALL :fn_UnsetVariable ExtensionSdkDir - CALL :fn_UnsetVariable Framework35Version - CALL :fn_UnsetVariable FrameworkDir - CALL :fn_UnsetVariable FrameworkDir32 - CALL :fn_UnsetVariable FrameworkVersion - CALL :fn_UnsetVariable FrameworkVersion32 - CALL :fn_UnsetVariable FSHARPINSTALLDIR - CALL :fn_UnsetVariable INCLUDE - CALL :fn_UnsetVariable LIB - CALL :fn_UnsetVariable LIBPATH - CALL :fn_UnsetVariable Platform - REM CALL :fn_UnsetVariable VCINSTALLDIR - CALL :fn_UnsetVariable VSINSTALLDIR - CALL :fn_UnsetVariable WindowsPhoneKitDir - CALL :fn_UnsetVariable WindowsSdkDir - CALL :fn_UnsetVariable WindowsSdkDir_35 - CALL :fn_UnsetVariable WindowsSdkDir_old - - REM - REM NOTE: Reset the PATH here to the absolute bare minimum required. - REM - SET PATH=%TOOLPATH%;%SystemRoot%\System32;%SystemRoot% - - FOR %%B IN (%CONFIGURATIONS%) DO ( - REM - REM NOTE: When preparing the debug build, set the DEBUG and MEMDEBUG - REM environment variables to be picked up by the MSVC makefile - REM itself. - REM - IF /I "%%B" == "Debug" ( - SET DEBUG=2 - SET MEMDEBUG=1 - ) ELSE ( - CALL :fn_UnsetVariable DEBUG - CALL :fn_UnsetVariable MEMDEBUG - ) - - REM - REM NOTE: Launch a nested command shell to perform the following steps: - REM - REM 1. Setup the MSVC environment for this platform using the - REM official batch file. - REM - REM 2. Make sure that no stale build output files are present. - REM - REM 3. Build the "sqlite3.dll" and "sqlite3.lib" binaries for this - REM platform. - REM - REM 4. Copy the "sqlite3.dll" and "sqlite3.lib" binaries for this - REM platform to the platform-specific directory beneath the - REM binary directory. - REM - "%ComSpec%" /C ( - REM - REM NOTE: Attempt to setup the MSVC environment for this platform. - REM - %__ECHO3% CALL "%VCVARSALL%" %%P - - IF ERRORLEVEL 1 ( - ECHO Failed to call "%VCVARSALL%" for platform %%P. - GOTO errors - ) - - REM - REM NOTE: If this batch file is not running in "what-if" mode, check to - REM be sure we were actually able to setup the MSVC environment - REM as current versions of their official batch file do not set - REM the exit code upon failure. - REM - IF NOT DEFINED __ECHO3 ( - IF NOT DEFINED WindowsPhoneKitDir ( - IF NOT DEFINED WindowsSdkDir ( - ECHO Cannot build, Windows SDK not found for platform %%P. - GOTO errors - ) - ) - ) - - REM - REM NOTE: When using MSVC 2012, the native SDK path cannot simply use - REM the "lib" sub-directory beneath the location specified in the - REM WindowsSdkDir environment variable because that location does - REM not actually contain the necessary library files for x86. - REM This must be done for each iteration because it relies upon - REM the WindowsSdkDir environment variable being set by the batch - REM file used to setup the MSVC environment. - REM - IF DEFINED SET_NSDKLIBPATH ( - IF DEFINED WindowsPhoneKitDir ( - CALL :fn_CopyVariable WindowsPhoneKitDir NSDKLIBPATH - CALL :fn_AppendVariable NSDKLIBPATH \lib\x86 - ) ELSE IF DEFINED WindowsSdkDir ( - CALL :fn_CopyVariable WindowsSdkDir NSDKLIBPATH - - IF "%VisualStudioVersion%" == "12.0" ( - CALL :fn_AppendVariable NSDKLIBPATH \lib\winv6.3\um\x86 - ) ELSE ( - CALL :fn_AppendVariable NSDKLIBPATH \lib\win8\um\x86 - ) - ) - ) - - REM - REM NOTE: Unless prevented from doing so, invoke NMAKE with the MSVC - REM makefile to clean any stale build output from previous - REM iterations of this loop and/or previous runs of this batch - REM file, etc. - REM - IF NOT DEFINED NOCLEAN ( - %__ECHO% nmake -f Makefile.msc clean - - IF ERRORLEVEL 1 ( - ECHO Failed to clean for platform %%P. - GOTO errors - ) - ) ELSE ( - REM - REM NOTE: Even when the cleaning step has been disabled, we still - REM need to remove the build output for the files we are - REM specifically wanting to build for each platform. - REM - %__ECHO% DEL /Q *.lo sqlite3.dll sqlite3.lib sqlite3.pdb - ) - - REM - REM NOTE: Call NMAKE with the MSVC makefile to build the "sqlite3.dll" - REM binary. The x86 compiler will be used to compile the native - REM command line tools needed during the build process itself. - REM Also, disable looking for and/or linking to the native Tcl - REM runtime library. - REM - %__ECHO% nmake -f Makefile.msc sqlite3.dll XCOMPILE=1 USE_NATIVE_LIBPATHS=1 NO_TCL=1 %NMAKE_ARGS% - - IF ERRORLEVEL 1 ( - ECHO Failed to build %%B "sqlite3.dll" for platform %%P. - GOTO errors - ) - - REM - REM NOTE: Copy the "sqlite3.dll" file to the appropriate directory for - REM the build and platform beneath the binary directory. - REM - %__ECHO% XCOPY sqlite3.dll "%BINARYDIRECTORY%\%%B\%%D\" %FFLAGS% %DFLAGS% - - IF ERRORLEVEL 1 ( - ECHO Failed to copy "sqlite3.dll" to "%BINARYDIRECTORY%\%%B\%%D\". - GOTO errors - ) - - REM - REM NOTE: Copy the "sqlite3.lib" file to the appropriate directory for - REM the build and platform beneath the binary directory. - REM - %__ECHO% XCOPY sqlite3.lib "%BINARYDIRECTORY%\%%B\%%D\" %FFLAGS% %DFLAGS% - - IF ERRORLEVEL 1 ( - ECHO Failed to copy "sqlite3.lib" to "%BINARYDIRECTORY%\%%B\%%D\". - GOTO errors - ) - - REM - REM NOTE: Copy the "sqlite3.pdb" file to the appropriate directory for - REM the build and platform beneath the binary directory unless we - REM are prevented from doing so. - REM - IF NOT DEFINED NOSYMBOLS ( - %__ECHO% XCOPY sqlite3.pdb "%BINARYDIRECTORY%\%%B\%%D\" %FFLAGS% %DFLAGS% - - IF ERRORLEVEL 1 ( - ECHO Failed to copy "sqlite3.pdb" to "%BINARYDIRECTORY%\%%B\%%D\". - GOTO errors - ) - ) - ) - ) - ) - - REM - REM NOTE: Handle any errors generated during the nested command shell. - REM - IF ERRORLEVEL 1 ( - GOTO errors - ) -) - -REM -REM NOTE: Restore the saved current directory from the directory stack. -REM -%__ECHO2% POPD - -IF ERRORLEVEL 1 ( - ECHO Could not restore directory. - GOTO errors -) - -REM -REM NOTE: If we get to this point, we have succeeded. -REM -GOTO no_errors - -:fn_ResetErrorLevel - VERIFY > NUL - GOTO :EOF - -:fn_SetErrorLevel - VERIFY MAYBE 2> NUL - GOTO :EOF - -:fn_CopyVariable - SETLOCAL - IF NOT DEFINED %1 GOTO :EOF - IF "%2" == "" GOTO :EOF - SET __ECHO_CMD=ECHO %%%1%% - FOR /F "delims=" %%V IN ('%__ECHO_CMD%') DO ( - SET VALUE=%%V - ) - ENDLOCAL && SET %2=%VALUE% - GOTO :EOF - -:fn_UnsetVariable - IF NOT "%1" == "" ( - SET %1= - CALL :fn_ResetErrorLevel - ) - GOTO :EOF - -:fn_AppendVariable - SET __ECHO_CMD=ECHO %%%1%% - IF DEFINED %1 ( - FOR /F "delims=" %%V IN ('%__ECHO_CMD%') DO ( - SET %1=%%V%~2 - ) - ) ELSE ( - SET %1=%~2 - ) - SET __ECHO_CMD= - CALL :fn_ResetErrorLevel - GOTO :EOF - -:usage - ECHO. - ECHO Usage: %~nx0 ^ - ECHO. - GOTO errors - -:errors - CALL :fn_SetErrorLevel - ENDLOCAL - ECHO. - ECHO Failure, errors were encountered. - GOTO end_of_file - -:no_errors - CALL :fn_ResetErrorLevel - ENDLOCAL - ECHO. - ECHO Success, no errors were encountered. - GOTO end_of_file - -:end_of_file -%__ECHO% EXIT /B %ERRORLEVEL% diff --git a/components/external/SQLite-3.8.1/tool/build-shell.sh b/components/external/SQLite-3.8.1/tool/build-shell.sh deleted file mode 100644 index 6a48299d73..0000000000 --- a/components/external/SQLite-3.8.1/tool/build-shell.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh -# -# This script demonstrates how to do a full-featured build of the sqlite3 -# command-line shell on Linux. -# -# SQLite source code should be in a sibling directory named "sqlite". For -# example, put SQLite sources in ~/sqlite/sqlite and run this script from -# ~/sqlite/bld. There should be an appropriate Makefile in the current -# directory as well. -# -make sqlite3.c -gcc -o sqlite3 -g -Os -I. \ - -DSQLITE_THREADSAFE=0 \ - -DSQLITE_ENABLE_VFSTRACE \ - -DSQLITE_ENABLE_STAT3 \ - -DSQLITE_ENABLE_FTS4 \ - -DSQLITE_ENABLE_RTREE \ - -DHAVE_READLINE \ - -DHAVE_USLEEP=1 \ - ../sqlite/src/shell.c \ - ../sqlite/src/test_vfstrace.c \ - sqlite3.c -ldl -lreadline -lncurses diff --git a/components/external/SQLite-3.8.1/tool/checkSpacing.c b/components/external/SQLite-3.8.1/tool/checkSpacing.c deleted file mode 100644 index ce38b08ce4..0000000000 --- a/components/external/SQLite-3.8.1/tool/checkSpacing.c +++ /dev/null @@ -1,84 +0,0 @@ -/* -** This program checks for formatting problems in source code: -** -** * Any use of tab characters -** * White space at the end of a line -** * Blank lines at the end of a file -** -** Any violations are reported. -*/ -#include -#include -#include - -#define CR_OK 0x001 -#define WSEOL_OK 0x002 - -static void checkSpacing(const char *zFile, unsigned flags){ - FILE *in = fopen(zFile, "rb"); - int i; - int seenSpace; - int seenTab; - int ln = 0; - int lastNonspace = 0; - char zLine[2000]; - if( in==0 ){ - printf("cannot open %s\n", zFile); - return; - } - while( fgets(zLine, sizeof(zLine), in) ){ - seenSpace = 0; - seenTab = 0; - ln++; - for(i=0; zLine[i]; i++){ - if( zLine[i]=='\t' && seenTab==0 ){ - printf("%s:%d: tab (\\t) character\n", zFile, ln); - seenTab = 1; - }else if( zLine[i]=='\r' ){ - if( (flags & CR_OK)==0 ){ - printf("%s:%d: carriage-return (\\r) character\n", zFile, ln); - } - }else if( zLine[i]==' ' ){ - seenSpace = 1; - }else if( zLine[i]!='\n' ){ - lastNonspace = ln; - seenSpace = 0; - } - } - if( seenSpace && (flags & WSEOL_OK)==0 ){ - printf("%s:%d: whitespace at end-of-line\n", zFile, ln); - } - } - fclose(in); - if( lastNonspace -#include -#include -#include -#include -#include -#include - - -#define PAGESIZE 1024 -static int db1 = -1; -static int db2 = -1; - -int main(int argc, char **argv){ - int iPg; - unsigned char a1[PAGESIZE], a2[PAGESIZE]; - if( argc!=3 ){ - fprintf(stderr,"Usage: %s FILENAME FILENAME\n", argv[0]); - exit(1); - } - db1 = open(argv[1], O_RDONLY); - if( db1<0 ){ - fprintf(stderr,"%s: can't open %s\n", argv[0], argv[1]); - exit(1); - } - db2 = open(argv[2], O_RDONLY); - if( db2<0 ){ - fprintf(stderr,"%s: can't open %s\n", argv[0], argv[2]); - exit(1); - } - iPg = 1; - while( read(db1, a1, PAGESIZE)==PAGESIZE && read(db2,a2,PAGESIZE)==PAGESIZE ){ - if( memcmp(a1,a2,PAGESIZE) ){ - printf("Page %d\n", iPg); - } - iPg++; - } - printf("%d pages checked\n", iPg-1); - close(db1); - close(db2); -} diff --git a/components/external/SQLite-3.8.1/tool/extract.c b/components/external/SQLite-3.8.1/tool/extract.c deleted file mode 100644 index 5bf5caa31c..0000000000 --- a/components/external/SQLite-3.8.1/tool/extract.c +++ /dev/null @@ -1,46 +0,0 @@ -/* -** Extract a range of bytes from a file. -** -** Usage: -** -** extract FILENAME OFFSET AMOUNT -** -** The bytes are written to standard output. -*/ -#include -#include - -int main(int argc, char **argv){ - FILE *f; - char *zBuf; - int ofst; - int n; - size_t got; - - if( argc!=4 ){ - fprintf(stderr, "Usage: %s FILENAME OFFSET AMOUNT\n", *argv); - return 1; - } - f = fopen(argv[1], "rb"); - if( f==0 ){ - fprintf(stderr, "cannot open \"%s\"\n", argv[1]); - return 1; - } - ofst = atoi(argv[2]); - n = atoi(argv[3]); - zBuf = malloc( n ); - if( zBuf==0 ){ - fprintf(stderr, "out of memory\n"); - return 1; - } - fseek(f, ofst, SEEK_SET); - got = fread(zBuf, 1, n, f); - fclose(f); - if( got -#include - -/* -** Finalize a prepared statement. If an error has occurred, print the -** error message and exit. -*/ -static void vacuumFinalize(sqlite3_stmt *pStmt){ - sqlite3 *db = sqlite3_db_handle(pStmt); - int rc = sqlite3_finalize(pStmt); - if( rc ){ - fprintf(stderr, "finalize error: %s\n", sqlite3_errmsg(db)); - exit(1); - } -} - -/* -** Execute zSql on database db. The SQL text is printed to standard -** output. If an error occurs, print an error message and exit the -** process. -*/ -static void execSql(sqlite3 *db, const char *zSql){ - sqlite3_stmt *pStmt; - if( !zSql ){ - fprintf(stderr, "out of memory!\n"); - exit(1); - } - printf("%s;\n", zSql); - if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){ - fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db)); - exit(1); - } - sqlite3_step(pStmt); - vacuumFinalize(pStmt); -} - -/* -** Execute zSql on database db. The zSql statement returns exactly -** one column. Execute this return value as SQL on the same database. -** -** The zSql statement is printed on standard output prior to being -** run. If any errors occur, an error is printed and the process -** exits. -*/ -static void execExecSql(sqlite3 *db, const char *zSql){ - sqlite3_stmt *pStmt; - int rc; - - printf("%s;\n", zSql); - rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); - if( rc!=SQLITE_OK ){ - fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db)); - exit(1); - } - while( SQLITE_ROW==sqlite3_step(pStmt) ){ - execSql(db, (char*)sqlite3_column_text(pStmt, 0)); - } - vacuumFinalize(pStmt); -} - - -int main(int argc, char **argv){ - sqlite3 *db; /* Connection to the database file */ - int rc; /* Return code from SQLite interface calls */ - sqlite3_uint64 r; /* A random number */ - const char *zDbToVacuum; /* Database to be vacuumed */ - char *zBackupDb; /* Backup copy of the original database */ - char *zTempDb; /* Temporary database */ - char *zSql; /* An SQL statement */ - - if( argc!=2 ){ - fprintf(stderr, "Usage: %s DATABASE\n", argv[0]); - return 1; - } - - /* Identify the database file to be vacuumed and open it. - */ - zDbToVacuum = argv[1]; - printf("-- open database file \"%s\"\n", zDbToVacuum); - rc = sqlite3_open(zDbToVacuum, &db); - if( rc ){ - fprintf(stderr, "%s: %s\n", zDbToVacuum, sqlite3_errstr(rc)); - return 1; - } - - /* Create names for two other files. zTempDb will be a new database - ** into which we construct a vacuumed copy of zDbToVacuum. zBackupDb - ** will be a new name for zDbToVacuum after it is vacuumed. - */ - sqlite3_randomness(sizeof(r), &r); - zTempDb = sqlite3_mprintf("%s-vacuum-%016llx", zDbToVacuum, r); - zBackupDb = sqlite3_mprintf("%s-backup-%016llx", zDbToVacuum, r); - - /* Attach the zTempDb database to the database connection. - */ - zSql = sqlite3_mprintf("ATTACH '%q' AS vacuum_db;", zTempDb); - execSql(db, zSql); - sqlite3_free(zSql); - - /* TODO: - ** Set the page_size and auto_vacuum mode for zTempDb here, if desired. - */ - - /* The vacuum will occur inside of a transaction. Set writable_schema - ** to ON so that we can directly update the sqlite_master table in the - ** zTempDb database. - */ - execSql(db, "PRAGMA writable_schema=ON"); - execSql(db, "BEGIN"); - - - /* Query the schema of the main database. Create a mirror schema - ** in the temporary database. - */ - execExecSql(db, - "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) " - " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'" - " AND rootpage>0" - ); - execExecSql(db, - "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)" - " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %'" - ); - execExecSql(db, - "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) " - " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'" - ); - - /* Loop through the tables in the main database. For each, do - ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy - ** the contents to the temporary database. - */ - execExecSql(db, - "SELECT 'INSERT INTO vacuum_db.' || quote(name) " - "|| ' SELECT * FROM main.' || quote(name) " - "FROM main.sqlite_master " - "WHERE type = 'table' AND name!='sqlite_sequence' " - " AND rootpage>0" - ); - - /* Copy over the sequence table - */ - execExecSql(db, - "SELECT 'DELETE FROM vacuum_db.' || quote(name) " - "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence'" - ); - execExecSql(db, - "SELECT 'INSERT INTO vacuum_db.' || quote(name) " - "|| ' SELECT * FROM main.' || quote(name) " - "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence'" - ); - - /* Copy the triggers, views, and virtual tables from the main database - ** over to the temporary database. None of these objects has any - ** associated storage, so all we have to do is copy their entries - ** from the SQLITE_MASTER table. - */ - execSql(db, - "INSERT INTO vacuum_db.sqlite_master " - " SELECT type, name, tbl_name, rootpage, sql" - " FROM main.sqlite_master" - " WHERE type='view' OR type='trigger'" - " OR (type='table' AND rootpage=0)" - ); - - /* Commit the transaction and close the database - */ - execSql(db, "COMMIT"); - printf("-- close database\n"); - sqlite3_close(db); - - - /* At this point, zDbToVacuum is unchanged. zTempDb contains a - ** vacuumed copy of zDbToVacuum. Rearrange filenames so that - ** zTempDb becomes thenew zDbToVacuum. - */ - printf("-- rename \"%s\" to \"%s\"\n", zDbToVacuum, zBackupDb); - rename(zDbToVacuum, zBackupDb); - printf("-- rename \"%s\" to \"%s\"\n", zTempDb, zDbToVacuum); - rename(zTempDb, zDbToVacuum); - - /* Release allocated memory */ - sqlite3_free(zTempDb); - sqlite3_free(zBackupDb); - return 0; -} diff --git a/components/external/SQLite-3.8.1/tool/fragck.tcl b/components/external/SQLite-3.8.1/tool/fragck.tcl deleted file mode 100644 index 35e76f482b..0000000000 --- a/components/external/SQLite-3.8.1/tool/fragck.tcl +++ /dev/null @@ -1,149 +0,0 @@ -# Run this TCL script using "testfixture" to get a report that shows -# the sequence of database pages used by a particular table or index. -# This information is used for fragmentation analysis. -# - -# Get the name of the database to analyze -# - -if {[llength $argv]!=2} { - puts stderr "Usage: $argv0 database-name table-or-index-name" - exit 1 -} -set file_to_analyze [lindex $argv 0] -if {![file exists $file_to_analyze]} { - puts stderr "No such file: $file_to_analyze" - exit 1 -} -if {![file readable $file_to_analyze]} { - puts stderr "File is not readable: $file_to_analyze" - exit 1 -} -if {[file size $file_to_analyze]<512} { - puts stderr "Empty or malformed database: $file_to_analyze" - exit 1 -} -set objname [lindex $argv 1] - -# Open the database -# -sqlite3 db [lindex $argv 0] -set DB [btree_open [lindex $argv 0] 1000 0] - -# This proc is a wrapper around the btree_cursor_info command. The -# second argument is an open btree cursor returned by [btree_cursor]. -# The first argument is the name of an array variable that exists in -# the scope of the caller. If the third argument is non-zero, then -# info is returned for the page that lies $up entries upwards in the -# tree-structure. (i.e. $up==1 returns the parent page, $up==2 the -# grandparent etc.) -# -# The following entries in that array are filled in with information retrieved -# using [btree_cursor_info]: -# -# $arrayvar(page_no) = The page number -# $arrayvar(entry_no) = The entry number -# $arrayvar(page_entries) = Total number of entries on this page -# $arrayvar(cell_size) = Cell size (local payload + header) -# $arrayvar(page_freebytes) = Number of free bytes on this page -# $arrayvar(page_freeblocks) = Number of free blocks on the page -# $arrayvar(payload_bytes) = Total payload size (local + overflow) -# $arrayvar(header_bytes) = Header size in bytes -# $arrayvar(local_payload_bytes) = Local payload size -# $arrayvar(parent) = Parent page number -# -proc cursor_info {arrayvar csr {up 0}} { - upvar $arrayvar a - foreach [list a(page_no) \ - a(entry_no) \ - a(page_entries) \ - a(cell_size) \ - a(page_freebytes) \ - a(page_freeblocks) \ - a(payload_bytes) \ - a(header_bytes) \ - a(local_payload_bytes) \ - a(parent) \ - a(first_ovfl) ] [btree_cursor_info $csr $up] break -} - -# Determine the page-size of the database. This global variable is used -# throughout the script. -# -set pageSize [db eval {PRAGMA page_size}] - -# Find the root page of table or index to be analyzed. Also find out -# if the object is a table or an index. -# -if {$objname=="sqlite_master"} { - set rootpage 1 - set type table -} else { - db eval { - SELECT rootpage, type FROM sqlite_master - WHERE name=$objname - } break - if {![info exists rootpage]} { - puts stderr "no such table or index: $objname" - exit 1 - } - if {$type!="table" && $type!="index"} { - puts stderr "$objname is something other than a table or index" - exit 1 - } - if {![string is integer -strict $rootpage]} { - puts stderr "invalid root page for $objname: $rootpage" - exit 1 - } -} - -# The cursor $csr is pointing to an entry. Print out information -# about the page that $up levels above that page that contains -# the entry. If $up==0 use the page that contains the entry. -# -# If information about the page has been printed already, then -# this is a no-op. -# -proc page_info {csr up} { - global seen - cursor_info ci $csr $up - set pg $ci(page_no) - if {[info exists seen($pg)]} return - set seen($pg) 1 - - # Do parent pages first - # - if {$ci(parent)} { - page_info $csr [expr {$up+1}] - } - - # Find the depth of this page - # - set depth 1 - set i $up - while {$ci(parent)} { - incr i - incr depth - cursor_info ci $csr $i - } - - # print the results - # - puts [format {LEVEL %d: %6d} $depth $pg] -} - - - - -# Loop through the object and print out page numbers -# -set csr [btree_cursor $DB $rootpage 0] -for {btree_first $csr} {![btree_eof $csr]} {btree_next $csr} { - page_info $csr 0 - set i 1 - foreach pg [btree_ovfl_info $DB $csr] { - puts [format {OVFL %3d: %6d} $i $pg] - incr i - } -} -exit 0 diff --git a/components/external/SQLite-3.8.1/tool/genfkey.README b/components/external/SQLite-3.8.1/tool/genfkey.README deleted file mode 100644 index 57cdff87f8..0000000000 --- a/components/external/SQLite-3.8.1/tool/genfkey.README +++ /dev/null @@ -1,137 +0,0 @@ - -OVERVIEW - - The SQLite library is capable of parsing SQL foreign key constraints - supplied as part of CREATE TABLE statements, but it does not actually - implement them. However, most of the features of foreign keys may be - implemented using SQL triggers, which SQLite does support. This text - file describes a feature of the SQLite shell tool (sqlite3) that - extracts foreign key definitions from an existing SQLite database and - creates the set of CREATE TRIGGER statements required to implement - the foreign key constraints. - -CAPABILITIES - - An SQL foreign key is a constraint that requires that each row in - the "child" table corresponds to a row in the "parent" table. For - example, the following schema: - - CREATE TABLE parent(a, b, c, PRIMARY KEY(a, b)); - CREATE TABLE child(d, e, f, FOREIGN KEY(d, e) REFERENCES parent(a, b)); - - implies that for each row in table "child", there must be a row in - "parent" for which the expression (child.d==parent.a AND child.e==parent.b) - is true. The columns in the parent table are required to be either the - primary key columns or subject to a UNIQUE constraint. There is no such - requirement for the columns of the child table. - - At this time, all foreign keys are implemented as if they were - "MATCH NONE", even if the declaration specified "MATCH PARTIAL" or - "MATCH FULL". "MATCH NONE" means that if any of the key columns in - the child table are NULL, then there is no requirement for a corresponding - row in the parent table. So, taking this into account, the expression that - must be true for every row of the child table in the above example is - actually: - - (child.d IS NULL) OR - (child.e IS NULL) OR - (child.d==parent.a AND child.e==parent.b) - - Attempting to insert or update a row in the child table so that the - affected row violates this constraint results in an exception being - thrown. - - The effect of attempting to delete or update a row in the parent table - so that the constraint becomes untrue for one or more rows in the child - table depends on the "ON DELETE" or "ON UPDATE" actions specified as - part of the foreign key definition, respectively. Three different actions - are supported: "RESTRICT" (the default), "CASCADE" and "SET NULL". SQLite - will also parse the "SET DEFAULT" action, but this is not implemented - and "RESTRICT" is used instead. - - RESTRICT: Attempting to update or delete a row in the parent table so - that the constraint becomes untrue for one or more rows in - the child table is not allowed. An exception is thrown. - - CASCADE: Instead of throwing an exception, all corresponding child table - rows are either deleted (if the parent row is being deleted) - or updated to match the new parent key values (if the parent - row is being updated). - - SET NULL: Instead of throwing an exception, the foreign key fields of - all corresponding child table rows are set to NULL. - -LIMITATIONS - - Apart from those limitiations described above: - - * Implicit mapping to composite primary keys is not supported. If - a parent table has a composite primary key, then any child table - that refers to it must explicitly map each column. For example, given - the following definition of table "parent": - - CREATE TABLE parent(a, b, c, PRIMARY KEY(a, b)); - - only the first of the following two definitions of table "child" - is supported: - - CREATE TABLE child(d, e, f, FOREIGN KEY(d, e) REFERENCES parent(a, b)); - CREATE TABLE child(d, e, f, FOREIGN KEY(d, e) REFERENCES parent); - - An implicit reference to a composite primary key is detected as an - error when the program is run (see below). - - * SQLite does not support recursive triggers, and therefore this program - does not support recursive CASCADE or SET NULL foreign key - relationships. If the parent and the child tables of a CASCADE or - SET NULL foreign key are the same table, the generated triggers will - malfunction. This is also true if the recursive foreign key constraint - is indirect (for example if table A references table B which references - table A with a CASCADE or SET NULL foreign key constraint). - - Recursive CASCADE or SET NULL foreign key relationships are *not* - detected as errors when the program is run. Buyer beware. - -USAGE - - The functionality is accessed through an sqlite3 shell tool "dot-command": - - .genfkey ?--no-drop? ?--ignore-errors? ?--exec? - - When this command is run, it first checks the schema of the open SQLite - database for foreign key related errors or inconsistencies. For example, - a foreign key that refers to a parent table that does not exist, or - a foreign key that refers to columns in a parent table that are not - guaranteed to be unique. If such errors are found and the --ignore-errors - option was not present, a message for each one is printed to stderr and - no further processing takes place. - - If errors are found and the --ignore-errors option is passed, then - no error messages are printed. No "CREATE TRIGGER" statements are generated - for foriegn-key definitions that contained errors, they are silently - ignored by subsequent processing. - - All triggers generated by this command have names that match the pattern - "genfkey*". Unless the --no-drop option is specified, then the program - also generates a "DROP TRIGGER" statement for each trigger that exists - in the database with a name that matches this pattern. This allows the - program to be used to upgrade a database schema for which foreign key - triggers have already been installed (i.e. after new tables are created - or existing tables dropped). - - Finally, a series of SQL trigger definitions (CREATE TRIGGER statements) - that implement the foreign key constraints found in the database schema are - generated. - - If the --exec option was passed, then all generated SQL is immediately - executed on the database. Otherwise, the generated SQL strings are output - in the same way as the results of SELECT queries are. Normally, this means - they will be printed to stdout, but this can be configured using other - dot-commands (i.e. ".output"). - - The simplest way to activate the foriegn key definitions in a database - is simply to open it using the shell tool and enter the command - ".genfkey --exec": - - sqlite> .genfkey --exec - diff --git a/components/external/SQLite-3.8.1/tool/genfkey.test b/components/external/SQLite-3.8.1/tool/genfkey.test deleted file mode 100644 index 3c0073e953..0000000000 --- a/components/external/SQLite-3.8.1/tool/genfkey.test +++ /dev/null @@ -1,354 +0,0 @@ - -package require sqlite3 - -proc do_test {name cmd expected} { - puts -nonewline "$name ..." - set res [uplevel $cmd] - if {$res eq $expected} { - puts Ok - } else { - puts Error - puts " Got: $res" - puts " Expected: $expected" - exit - } -} - -proc execsql {sql} { - uplevel [list db eval $sql] -} - -proc catchsql {sql} { - set rc [catch {uplevel [list db eval $sql]} msg] - list $rc $msg -} - -file delete -force test.db test.db.journal -sqlite3 db test.db - -# The following tests - genfkey-1.* - test RESTRICT foreign keys. -# -do_test genfkey-1.1 { - execsql { - CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c)); - CREATE TABLE t2(e REFERENCES t1, f); - CREATE TABLE t3(g, h, i, FOREIGN KEY (h, i) REFERENCES t1(b, c)); - } -} {} -do_test genfkey-1.2 { - execsql [exec ./sqlite3 test.db .genfkey] -} {} -do_test genfkey-1.3 { - catchsql { INSERT INTO t2 VALUES(1, 2) } -} {1 {constraint failed}} -do_test genfkey-1.4 { - execsql { - INSERT INTO t1 VALUES(1, 2, 3); - INSERT INTO t2 VALUES(1, 2); - } -} {} -do_test genfkey-1.5 { - execsql { INSERT INTO t2 VALUES(NULL, 3) } -} {} -do_test genfkey-1.6 { - catchsql { UPDATE t2 SET e = 5 WHERE e IS NULL } -} {1 {constraint failed}} -do_test genfkey-1.7 { - execsql { UPDATE t2 SET e = 1 WHERE e IS NULL } -} {} -do_test genfkey-1.8 { - execsql { UPDATE t2 SET e = NULL WHERE f = 3 } -} {} -do_test genfkey-1.9 { - catchsql { UPDATE t1 SET a = 10 } -} {1 {constraint failed}} -do_test genfkey-1.9a { - catchsql { UPDATE t1 SET a = NULL } -} {1 {datatype mismatch}} -do_test genfkey-1.10 { - catchsql { DELETE FROM t1 } -} {1 {constraint failed}} -do_test genfkey-1.11 { - execsql { UPDATE t2 SET e = NULL } -} {} -do_test genfkey-1.12 { - execsql { - UPDATE t1 SET a = 10 ; - DELETE FROM t1; - DELETE FROM t2; - } -} {} - -do_test genfkey-1.13 { - execsql { - INSERT INTO t3 VALUES(1, NULL, NULL); - INSERT INTO t3 VALUES(1, 2, NULL); - INSERT INTO t3 VALUES(1, NULL, 3); - } -} {} -do_test genfkey-1.14 { - catchsql { INSERT INTO t3 VALUES(3, 1, 4) } -} {1 {constraint failed}} -do_test genfkey-1.15 { - execsql { - INSERT INTO t1 VALUES(1, 1, 4); - INSERT INTO t3 VALUES(3, 1, 4); - } -} {} -do_test genfkey-1.16 { - catchsql { DELETE FROM t1 } -} {1 {constraint failed}} -do_test genfkey-1.17 { - catchsql { UPDATE t1 SET b = 10} -} {1 {constraint failed}} -do_test genfkey-1.18 { - execsql { UPDATE t1 SET a = 10} -} {} -do_test genfkey-1.19 { - catchsql { UPDATE t3 SET h = 'hello' WHERE i = 3} -} {1 {constraint failed}} - -do_test genfkey-1.X { - execsql { - DROP TABLE t1; - DROP TABLE t2; - DROP TABLE t3; - } -} {} - -# The following tests - genfkey-2.* - test CASCADE foreign keys. -# -do_test genfkey-2.1 { - execsql { - CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(b, c)); - CREATE TABLE t2(e REFERENCES t1 ON UPDATE CASCADE ON DELETE CASCADE, f); - CREATE TABLE t3(g, h, i, - FOREIGN KEY (h, i) - REFERENCES t1(b, c) ON UPDATE CASCADE ON DELETE CASCADE - ); - } -} {} -do_test genfkey-2.2 { - execsql [exec ./sqlite3 test.db .genfkey] -} {} -do_test genfkey-2.3 { - execsql { - INSERT INTO t1 VALUES(1, 2, 3); - INSERT INTO t1 VALUES(4, 5, 6); - INSERT INTO t2 VALUES(1, 'one'); - INSERT INTO t2 VALUES(4, 'four'); - } -} {} -do_test genfkey-2.4 { - execsql { - UPDATE t1 SET a = 2 WHERE a = 1; - SELECT * FROM t2; - } -} {2 one 4 four} -do_test genfkey-2.5 { - execsql { - DELETE FROM t1 WHERE a = 4; - SELECT * FROM t2; - } -} {2 one} -do_test genfkey-2.6 { - execsql { - INSERT INTO t3 VALUES('hello', 2, 3); - UPDATE t1 SET c = 2; - SELECT * FROM t3; - } -} {hello 2 2} -do_test genfkey-2.7 { - execsql { - DELETE FROM t1; - SELECT * FROM t3; - } -} {} -do_test genfkey-2.X { - execsql { - DROP TABLE t1; - DROP TABLE t2; - DROP TABLE t3; - } -} {} - - -# The following tests - genfkey-3.* - test SET NULL foreign keys. -# -do_test genfkey-3.1 { - execsql { - CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, UNIQUE(c, b)); - CREATE TABLE t2(e REFERENCES t1 ON UPDATE SET NULL ON DELETE SET NULL, f); - CREATE TABLE t3(g, h, i, - FOREIGN KEY (h, i) - REFERENCES t1(b, c) ON UPDATE SET NULL ON DELETE SET NULL - ); - } -} {} -do_test genfkey-3.2 { - execsql [exec ./sqlite3 test.db .genfkey] -} {} -do_test genfkey-3.3 { - execsql { - INSERT INTO t1 VALUES(1, 2, 3); - INSERT INTO t1 VALUES(4, 5, 6); - INSERT INTO t2 VALUES(1, 'one'); - INSERT INTO t2 VALUES(4, 'four'); - } -} {} -do_test genfkey-3.4 { - execsql { - UPDATE t1 SET a = 2 WHERE a = 1; - SELECT * FROM t2; - } -} {{} one 4 four} -do_test genfkey-3.5 { - execsql { - DELETE FROM t1 WHERE a = 4; - SELECT * FROM t2; - } -} {{} one {} four} -do_test genfkey-3.6 { - execsql { - INSERT INTO t3 VALUES('hello', 2, 3); - UPDATE t1 SET c = 2; - SELECT * FROM t3; - } -} {hello {} {}} -do_test genfkey-2.7 { - execsql { - UPDATE t3 SET h = 2, i = 2; - DELETE FROM t1; - SELECT * FROM t3; - } -} {hello {} {}} -do_test genfkey-3.X { - execsql { - DROP TABLE t1; - DROP TABLE t2; - DROP TABLE t3; - } -} {} - -# The following tests - genfkey-4.* - test that errors in the schema -# are detected correctly. -# -do_test genfkey-4.1 { - execsql { - CREATE TABLE t1(a REFERENCES nosuchtable, b); - CREATE TABLE t2(a REFERENCES t1, b); - - CREATE TABLE t3(a, b, c, PRIMARY KEY(a, b)); - CREATE TABLE t4(a, b, c, FOREIGN KEY(c, b) REFERENCES t3); - - CREATE TABLE t5(a REFERENCES t4(d), b, c); - CREATE TABLE t6(a REFERENCES t4(a), b, c); - CREATE TABLE t7(a REFERENCES t3(a), b, c); - CREATE TABLE t8(a REFERENCES nosuchtable(a), b, c); - } -} {} - -do_test genfkey-4.X { - set rc [catch {exec ./sqlite3 test.db .genfkey} msg] - list $rc $msg -} "1 {[string trim { -Error in table t5: foreign key columns do not exist -Error in table t8: foreign key columns do not exist -Error in table t4: implicit mapping to composite primary key -Error in table t1: implicit mapping to non-existant primary key -Error in table t2: implicit mapping to non-existant primary key -Error in table t6: foreign key is not unique -Error in table t7: foreign key is not unique -}]}" - -# Test that ticket #3800 has been resolved. -# -do_test genfkey-5.1 { - execsql { - DROP TABLE t1; DROP TABLE t2; DROP TABLE t3; - DROP TABLE t4; DROP TABLE t5; DROP TABLE t6; - DROP TABLE t7; DROP TABLE t8; - } -} {} -do_test genfkey-5.2 { - execsql { - CREATE TABLE "t.3" (c1 PRIMARY KEY); - CREATE TABLE t13 (c1, foreign key(c1) references "t.3"(c1)); - } -} {} -do_test genfkey-5.3 { - set rc [catch {exec ./sqlite3 test.db .genfkey} msg] -} {0} -do_test genfkey-5.4 { - db eval $msg -} {} -do_test genfkey-5.5 { - catchsql { INSERT INTO t13 VALUES(1) } -} {1 {constraint failed}} -do_test genfkey-5.5 { - catchsql { - INSERT INTO "t.3" VALUES(1); - INSERT INTO t13 VALUES(1); - } -} {0 {}} - -# Test also column names that require quoting. -do_test genfkey-6.1 { - execsql { - DROP TABLE "t.3"; - DROP TABLE t13; - CREATE TABLE p( - "a.1 first", "b.2 second", - UNIQUE("a.1 first", "b.2 second") - ); - CREATE TABLE c( - "c.1 I", "d.2 II", - FOREIGN KEY("c.1 I", "d.2 II") - REFERENCES p("a.1 first", "b.2 second") - ON UPDATE CASCADE ON DELETE CASCADE - ); - } -} {} -do_test genfkey-6.2 { - set rc [catch {exec ./sqlite3 test.db .genfkey} msg] -} {0} -do_test genfkey-6.3 { - execsql $msg - execsql { - INSERT INTO p VALUES('A', 'B'); - INSERT INTO p VALUES('C', 'D'); - INSERT INTO c VALUES('A', 'B'); - INSERT INTO c VALUES('C', 'D'); - UPDATE p SET "a.1 first" = 'X' WHERE rowid = 1; - DELETE FROM p WHERE rowid = 2; - } - execsql { SELECT * FROM c } -} {X B} - -do_test genfkey-6.4 { - execsql { - DROP TABLE p; - DROP TABLE c; - CREATE TABLE parent("a.1", PRIMARY KEY("a.1")); - CREATE TABLE child("b.2", FOREIGN KEY("b.2") REFERENCES parent("a.1")); - } - set rc [catch {exec ./sqlite3 test.db .genfkey} msg] -} {0} -do_test genfkey-6.5 { - execsql $msg - execsql { - INSERT INTO parent VALUES(1); - INSERT INTO child VALUES(1); - } - catchsql { UPDATE parent SET "a.1"=0 } -} {1 {constraint failed}} -do_test genfkey-6.6 { - catchsql { UPDATE child SET "b.2"=7 } -} {1 {constraint failed}} -do_test genfkey-6.7 { - execsql { - SELECT * FROM parent; - SELECT * FROM child; - } -} {1 1} - diff --git a/components/external/SQLite-3.8.1/tool/getlock.c b/components/external/SQLite-3.8.1/tool/getlock.c deleted file mode 100644 index 7eff04d7f9..0000000000 --- a/components/external/SQLite-3.8.1/tool/getlock.c +++ /dev/null @@ -1,134 +0,0 @@ -/* -** This utility program looks at an SQLite database and determines whether -** or not it is locked, the kind of lock, and who is holding this lock. -** -** This only works on unix when the posix advisory locking method is used -** (which is the default on unix) and when the PENDING_BYTE is in its -** usual place. -*/ -#include -#include -#include -#include -#include -#include -#include -#include - -static void usage(const char *argv0){ - fprintf(stderr, "Usage: %s database\n", argv0); - exit(1); -} - -/* Check for a conflicting lock. If one is found, print an this -** on standard output using the format string given and return 1. -** If there are no conflicting locks, return 0. -*/ -static int isLocked( - int h, /* File descriptor to check */ - int type, /* F_RDLCK or F_WRLCK */ - unsigned int iOfst, /* First byte of the lock */ - unsigned int iCnt, /* Number of bytes in the lock range */ - const char *zType /* Type of lock */ -){ - struct flock lk; - - memset(&lk, 0, sizeof(lk)); - lk.l_type = type; - lk.l_whence = SEEK_SET; - lk.l_start = iOfst; - lk.l_len = iCnt; - if( fcntl(h, F_GETLK, &lk)==(-1) ){ - fprintf(stderr, "fcntl(%d) failed: errno=%d\n", h, errno); - exit(1); - } - if( lk.l_type==F_UNLCK ) return 0; - printf("%s lock held by %d\n", zType, (int)lk.l_pid); - return 1; -} - -/* -** Location of locking bytes in the database file -*/ -#define PENDING_BYTE (0x40000000) -#define RESERVED_BYTE (PENDING_BYTE+1) -#define SHARED_FIRST (PENDING_BYTE+2) -#define SHARED_SIZE 510 - -/* -** Lock locations for shared-memory locks used by WAL mode. -*/ -#define SHM_BASE 120 -#define SHM_WRITE SHM_BASE -#define SHM_CHECKPOINT (SHM_BASE+1) -#define SHM_RECOVER (SHM_BASE+2) -#define SHM_READ_FIRST (SHM_BASE+3) -#define SHM_READ_SIZE 5 - - -int main(int argc, char **argv){ - int hDb; /* File descriptor for the open database file */ - int hShm; /* File descriptor for WAL shared-memory file */ - char *zShm; /* Name of the shared-memory file for WAL mode */ - ssize_t got; /* Bytes read from header */ - int isWal; /* True if in WAL mode */ - int nName; /* Length of filename */ - unsigned char aHdr[100]; /* Database header */ - int nLock = 0; /* Number of locks held */ - int i; /* Loop counter */ - - if( argc!=2 ) usage(argv[0]); - hDb = open(argv[1], O_RDONLY, 0); - if( hDb<0 ){ - fprintf(stderr, "cannot open %s\n", argv[1]); - return 1; - } - - /* Make sure we are dealing with an database file */ - got = read(hDb, aHdr, 100); - if( got!=100 || memcmp(aHdr, "SQLite format 3",16)!=0 ){ - fprintf(stderr, "not an SQLite database: %s\n", argv[1]); - exit(1); - } - - /* First check for an exclusive lock */ - if( isLocked(hDb, F_RDLCK, SHARED_FIRST, SHARED_SIZE, "EXCLUSIVE") ){ - return 0; - } - isWal = aHdr[18]==2; - if( isWal==0 ){ - /* Rollback mode */ - if( isLocked(hDb, F_RDLCK, PENDING_BYTE, 1, "PENDING") ) return 0; - if( isLocked(hDb, F_RDLCK, RESERVED_BYTE, 1, "RESERVED") ) return 0; - if( isLocked(hDb, F_WRLCK, SHARED_FIRST, SHARED_SIZE, "SHARED") ){ - return 0; - } - }else{ - /* WAL mode */ - nName = (int)strlen(argv[1]); - zShm = malloc( nName + 100 ); - if( zShm==0 ){ - fprintf(stderr, "out of memory\n"); - exit(1); - } - memcpy(zShm, argv[1], nName); - memcpy(&zShm[nName], "-shm", 5); - hShm = open(zShm, O_RDONLY, 0); - if( hShm<0 ){ - fprintf(stderr, "cannot open %s\n", zShm); - return 1; - } - if( isLocked(hShm, F_RDLCK, SHM_RECOVER, 1, "WAL-RECOVERY") ){ - return 0; - } - nLock += isLocked(hShm, F_RDLCK, SHM_CHECKPOINT, 1, "WAL-CHECKPOINT"); - nLock += isLocked(hShm, F_RDLCK, SHM_WRITE, 1, "WAL-WRITE"); - for(i=0; i -#include -#include -#include -#include -#include - -#ifndef __WIN32__ -# if defined(_WIN32) || defined(WIN32) -# define __WIN32__ -# endif -#endif - -#ifdef __WIN32__ -#ifdef __cplusplus -extern "C" { -#endif -extern int access(const char *path, int mode); -#ifdef __cplusplus -} -#endif -#else -#include -#endif - -/* #define PRIVATE static */ -#define PRIVATE - -#ifdef TEST -#define MAXRHS 5 /* Set low to exercise exception code */ -#else -#define MAXRHS 1000 -#endif - -static int showPrecedenceConflict = 0; -static char *msort(char*,char**,int(*)(const char*,const char*)); - -/* -** Compilers are getting increasingly pedantic about type conversions -** as C evolves ever closer to Ada.... To work around the latest problems -** we have to define the following variant of strlen(). -*/ -#define lemonStrlen(X) ((int)strlen(X)) - -/* a few forward declarations... */ -struct rule; -struct lemon; -struct action; - -static struct action *Action_new(void); -static struct action *Action_sort(struct action *); - -/********** 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(struct lemon *); -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" ******************************************/ -enum option_type { OPT_FLAG=1, OPT_INT, OPT_DBL, OPT_STR, - OPT_FFLAG, OPT_FINT, OPT_FDBL, OPT_FSTR}; -struct s_options { - enum option_type type; - const char *label; - char *arg; - const 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 *, int); -void ReportHeader(struct lemon *); -void CompressTables(struct lemon *); -void ResortStates(struct lemon *); - -/********** From the file "set.h" ****************************************/ -void SetSize(int); /* 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 *,char *); /* 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 {LEMON_FALSE=0, LEMON_TRUE} Boolean; - -/* Symbols (terminals and nonterminals) of the grammar are stored -** in the following: */ -enum symbol_type { - TERMINAL, - NONTERMINAL, - MULTITERMINAL -}; -enum e_assoc { - LEFT, - RIGHT, - NONE, - UNK -}; -struct symbol { - const char *name; /* Name of the symbol */ - int index; /* Index number for this symbol */ - enum symbol_type 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 assoc; /* Associativity if precedence is defined */ - char *firstset; /* First-set for all rules of this symbol */ - Boolean lambda; /* True if NT and can generate an empty string */ - int useCnt; /* Number of times used */ - char *destructor; /* Code which executes whenever this symbol is - ** popped from the stack during error processing */ - int destLineno; /* Line number for start of destructor */ - 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 */ - /* The following fields are used by MULTITERMINALs only */ - int nsubsym; /* Number of constituent symbols in the MULTI */ - struct symbol **subsym; /* Array of constituent symbols */ -}; - -/* Each production rule in the grammar is stored in the following -** structure. */ -struct rule { - struct symbol *lhs; /* Left-hand side of the rule */ - const char *lhsalias; /* Alias for the LHS (NULL if none) */ - int lhsStart; /* True if left-hand side is the start symbol */ - int ruleline; /* Line number for the rule */ - int nrhs; /* Number of RHS symbols */ - struct symbol **rhs; /* The RHS symbols */ - const char **rhsalias; /* An alias for each RHS symbol (NULL if none) */ - int line; /* Line number at which code begins */ - const 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: */ -enum cfgstatus { - COMPLETE, - INCOMPLETE -}; -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 cfgstatus status; /* used during followset and shift computations */ - struct config *next; /* Next configuration in the state */ - struct config *bp; /* The next basis configuration */ -}; - -enum e_action { - SHIFT, - ACCEPT, - REDUCE, - ERROR, - SSCONFLICT, /* A shift/shift conflict */ - SRCONFLICT, /* Was a reduce, but part of a conflict */ - RRCONFLICT, /* 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 */ -}; - -/* Every shift or reduce operation is stored as one of the following */ -struct action { - struct symbol *sp; /* The look-ahead symbol */ - enum e_action 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 statenum; /* Sequential 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 */ - struct symbol *wildcard; /* Token that matches anything */ - 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 */ - char *error; /* Code to execute when an error is seen */ - char *overflow; /* Code to execute on a stack overflow */ - char *failure; /* Code to execute on parser failure */ - char *accept; /* Code to execute when the parser excepts */ - char *extracode; /* Code appended to the generated file */ - char *tokendest; /* Code to execute to destroy token data */ - char *vardest; /* Code for the default non-terminal destructor */ - 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 grammar */ - int nolinenosflag; /* True if #line statements should not be printed */ - 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 */ - -const char *Strsafe(const char *); - -void Strsafe_init(void); -int Strsafe_insert(const char *); -const char *Strsafe_find(const char *); - -/* Routines for handling symbols of the grammar */ - -struct symbol *Symbol_new(const char *); -int Symbolcmpp(const void *, const void *); -void Symbol_init(void); -int Symbol_insert(struct symbol *, const char *); -struct symbol *Symbol_find(const char *); -struct symbol *Symbol_Nth(int); -int Symbol_count(void); -struct symbol **Symbol_arrayof(void); - -/* Routines to manage the state table */ - -int Configcmp(const char *, const char *); -struct state *State_new(void); -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 */ -static struct action *Action_new(void){ - static struct action *freelist = 0; - struct action *newaction; - - if( freelist==0 ){ - int i; - int amt = 100; - freelist = (struct action *)calloc(amt, sizeof(struct action)); - if( freelist==0 ){ - fprintf(stderr,"Unable to allocate memory for a new parser action."); - exit(1); - } - for(i=0; inext; - return newaction; -} - -/* Compare two actions for sorting purposes. Return negative, zero, or -** positive if the first action is less than, equal to, or greater than -** the first -*/ -static int actioncmp( - 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 && ap1->type==REDUCE ){ - rc = ap1->x.rp->index - ap2->x.rp->index; - } - if( rc==0 ){ - rc = (int) (ap2 - ap1); - } - return rc; -} - -/* Sort parser actions */ -static struct action *Action_sort( - struct action *ap -){ - ap = (struct action *)msort((char *)ap,(char **)&ap->next, - (int(*)(const char*,const char*))actioncmp); - return ap; -} - -void Action_add( - struct action **app, - enum e_action type, - struct symbol *sp, - char *arg -){ - struct action *newaction; - newaction = Action_new(); - newaction->next = *app; - *app = newaction; - newaction->type = type; - newaction->sp = sp; - if( type==SHIFT ){ - newaction->x.stp = (struct state *)arg; - }else{ - newaction->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. -** -** The yy_action table maps the pair (state_number, lookahead) into an -** action_number. The table is an array of integers pairs. The state_number -** determines an initial offset into the yy_action array. The lookahead -** value is then added to this initial offset to get an index X into the -** yy_action array. If the aAction[X].lookahead equals the value of the -** of the lookahead input, then the value of the action_number output is -** aAction[X].action. If the lookaheads do not match then the -** default action for the state_number is returned. -** -** All actions associated with a single state_number are first entered -** into aLookahead[] using multiple calls to acttab_action(). Then the -** actions for that single state_number are placed into the aAction[] -** array with a single call to acttab_insert(). The acttab_insert() call -** also resets the aLookahead[] array in preparation for the next -** state number. -*/ -struct lookahead_action { - int lookahead; /* Value of the lookahead token */ - int action; /* Action to take on the given lookahead */ -}; -typedef struct acttab acttab; -struct acttab { - int nAction; /* Number of used slots in aAction[] */ - int nActionAlloc; /* Slots allocated for aAction[] */ - struct lookahead_action - *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 = (acttab *) calloc( 1, 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. -** -** This routine is called once for each lookahead for a particular -** state. -*/ -void acttab_action(acttab *p, int lookahead, int action){ - if( p->nLookahead>=p->nLookaheadAlloc ){ - p->nLookaheadAlloc += 25; - p->aLookahead = (struct lookahead_action *) 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 = (struct lookahead_action *) 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 that is a - ** duplicate of the current transaction set. Fall out of the loop - ** if and when the duplicate is found. - ** - ** i is the index in p->aAction[] where p->mnLookahead is inserted. - */ - for(i=p->nAction-1; i>=0; i--){ - if( p->aAction[i].lookahead==p->mnLookahead ){ - /* All lookaheads and actions in the aLookahead[] transaction - ** must match against the candidate aAction[i] entry. */ - 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; - - /* No possible lookahead value that is not in the aLookahead[] - ** transaction is allowed to match aAction[i] */ - 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; /* An exact match is found at offset i */ - } - } - } - - /* If no existing offsets exactly match the current transaction, find an - ** an empty offset in the aAction[] table in which we can add the - ** aLookahead[] transaction. - */ - if( i<0 ){ - /* Look for holes in the aAction[] table that fit the current - ** aLookahead[] transaction. Leave i set to the offset of the hole. - ** If no holes are found, i is left at p->nAction, which means the - ** transaction will be appended. */ - for(i=0; inActionAlloc - p->mxLookahead; 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 */ - } - } - } - } - /* 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 "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(struct lemon *xp) -{ - struct rule *rp; - for(rp=xp->rule; rp; rp=rp->next){ - if( rp->precsym==0 ){ - int i, j; - for(i=0; inrhs && rp->precsym==0; i++){ - struct symbol *sp = rp->rhs[i]; - if( sp->type==MULTITERMINAL ){ - for(j=0; jnsubsym; j++){ - if( sp->subsym[j]->prec>=0 ){ - rp->precsym = sp->subsym[j]; - break; - } - } - }else if( sp->prec>=0 ){ - rp->precsym = rp->rhs[i]; - } - } - } - } - 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(struct lemon *lemp) -{ - int i, j; - struct rule *rp; - int progress; - - for(i=0; insymbol; i++){ - lemp->symbols[i]->lambda = LEMON_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++){ - struct symbol *sp = rp->rhs[i]; - assert( sp->type==NONTERMINAL || sp->lambda==LEMON_FALSE ); - if( sp->lambda==LEMON_FALSE ) break; - } - if( i==rp->nrhs ){ - rp->lhs->lambda = LEMON_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( s2->type==MULTITERMINAL ){ - for(j=0; jnsubsym; j++){ - progress += SetAdd(s1->firstset,s2->subsym[j]->index); - } - break; - }else if( s1==s2 ){ - if( s1->lambda==LEMON_FALSE ) break; - }else{ - progress += SetUnion(s1->firstset,s2->firstset); - if( s2->lambda==LEMON_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(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 ){ /* FIX ME: Deal with multiterminals */ - 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; - rp->lhsStart = 1; - 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(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->statenum = 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; -} - -/* -** Return true if two symbols are the same. -*/ -int same_symbol(struct symbol *a, struct symbol *b) -{ - int i; - if( a==b ) return 1; - if( a->type!=MULTITERMINAL ) return 0; - if( b->type!=MULTITERMINAL ) return 0; - if( a->nsubsym!=b->nsubsym ) return 0; - for(i=0; insubsym; i++){ - if( a->subsym[i]!=b->subsym[i] ) return 0; - } - return 1; -} - -/* 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(struct lemon *lemp, struct state *stp) -{ - 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 *newcfg; /* */ - 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( !same_symbol(bsp,sp) ) continue; /* Must be same as for "cfp" */ - bcfp->status = COMPLETE; /* Mark this config as used */ - newcfg = Configlist_addbasis(bcfp->rp,bcfp->dot+1); - Plink_add(&newcfg->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" */ - if( sp->type==MULTITERMINAL ){ - int i; - for(i=0; insubsym; i++){ - Action_add(&stp->ap,SHIFT,sp->subsym[i],(char*)newstp); - } - }else{ - Action_add(&stp->ap,SHIFT,sp,(char *)newstp); - } - } -} - -/* -** Construct the propagation links -*/ -void FindLinks(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(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(struct action *,struct action *); - -/* Compute the reduce actions, and resolve conflicts. -*/ -void FindActions(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); - } - } - } - - /* Report an error for each rule that can never be reduced. */ - for(rp=lemp->rule; rp; rp=rp->next) rp->canReduce = LEMON_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 = LEMON_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 resolved, 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( - struct action *apx, - struct action *apy -){ - struct symbol *spx, *spy; - int errcnt = 0; - assert( apx->sp==apy->sp ); /* Otherwise there would be no conflict */ - if( apx->type==SHIFT && apy->type==SHIFT ){ - apy->type = SSCONFLICT; - errcnt++; - } - 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. */ - apy->type = SRCONFLICT; - errcnt++; - }else if( spx->prec>spy->prec ){ /* higher 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 ); - apy->type = SRCONFLICT; - 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 ){ - apy->type = RRCONFLICT; - 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==SSCONFLICT || - apx->type==SRCONFLICT || - apx->type==RRCONFLICT || - apy->type==SH_RESOLVED || - apy->type==RD_RESOLVED || - apy->type==SSCONFLICT || - apy->type==SRCONFLICT || - apy->type==RRCONFLICT - ); - /* 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 *newcfg; - if( freelist==0 ){ - int i; - int amt = 3; - freelist = (struct config *)calloc( amt, sizeof(struct config) ); - if( freelist==0 ){ - fprintf(stderr,"Unable to allocate memory for a new configuration."); - exit(1); - } - for(i=0; inext; - return newcfg; -} - -/* The configuration "old" is no longer used */ -PRIVATE void deleteconfig(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( - 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(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(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 if( xsp->type==MULTITERMINAL ){ - int k; - for(k=0; knsubsym; k++){ - SetAdd(newcfp->fws, xsp->subsym[k]->index); - } - break; - }else{ - SetUnion(newcfp->fws,xsp->firstset); - if( xsp->lambda==LEMON_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(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. -*/ - -void ErrorMsg(const char *filename, int lineno, const char *format, ...){ - va_list ap; - fprintf(stderr, "%s:%d: ", filename, lineno); - va_start(ap, format); - vfprintf(stderr,format,ap); - va_end(ap); - fprintf(stderr, "\n"); -} -/**************** 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 = (char **) realloc(azDefine, sizeof(azDefine[0])*nDefine); - if( azDefine==0 ){ - fprintf(stderr,"out of memory\n"); - exit(1); - } - paz = &azDefine[nDefine-1]; - *paz = (char *) malloc( lemonStrlen(z)+1 ); - if( *paz==0 ){ - fprintf(stderr,"out of memory\n"); - exit(1); - } - strcpy(*paz, z); - for(z=*paz; *z && *z!='='; z++){} - *z = 0; -} - -static char *user_templatename = NULL; -static void handle_T_option(char *z){ - user_templatename = (char *) malloc( lemonStrlen(z)+1 ); - if( user_templatename==0 ){ - memory_error(); - } - strcpy(user_templatename, z); -} - -/* The main program. Parse the command line and do it... */ -int main(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 int nolinenosflag = 0; - static int noResort = 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_FSTR, "T", (char*)handle_T_option, "Specify a template file."}, - {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."}, - {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file."}, - {OPT_FLAG, "l", (char*)&nolinenosflag, "Do not print #line statements."}, - {OPT_FLAG, "p", (char*)&showPrecedenceConflict, - "Show conflicts resolved by precedence rules"}, - {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."}, - {OPT_FLAG, "r", (char*)&noResort, "Do not sort or renumber states"}, - {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; - int exitcode; - 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); - } - memset(&lem, 0, sizeof(lem)); - lem.errorcnt = 0; - - /* Initialize the machine */ - Strsafe_init(); - Symbol_init(); - State_init(); - lem.argv0 = argv[0]; - lem.filename = OptArg(0); - lem.basisflag = basisflag; - lem.nolinenosflag = nolinenosflag; - Symbol_new("$"); - lem.errsym = Symbol_new("error"); - lem.errsym->useCnt = 0; - - /* Parse the input file */ - Parse(&lem); - if( lem.errorcnt ) exit(lem.errorcnt); - if( lem.nrule==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*), 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+1); - - /* 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); - - /* Reorder and renumber the states so that states with fewer choices - ** occur at the end. This is an optimization that helps make the - ** generated parser tables smaller. */ - if( noResort==0 ) ResortStates(&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 > 0 ){ - fprintf(stderr,"%d parsing conflicts.\n",lem.nconflict); - } - - /* return 0 on success, 1 on failure. */ - exitcode = ((lem.errorcnt > 0) || (lem.nconflict > 0)) ? 1 : 0; - exit(exitcode); - return (exitcode); -} -/******************** 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**)(((char*)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( - char *a, - char *b, - int (*cmp)(const char*,const char*), - 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 -static char *msort( - char *list, - char **next, - int (*cmp)(const char*,const char*) -){ - 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 no prior rule upon 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 *)calloc( sizeof(struct rule) + - sizeof(struct symbol*)*psp->nrhs + sizeof(char*)*psp->nrhs, 1); - 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 = (const 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 symbols on RHS of 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]=='|' || x[0]=='/') && psp->nrhs>0 ){ - struct symbol *msp = psp->rhs[psp->nrhs-1]; - if( msp->type!=MULTITERMINAL ){ - struct symbol *origsp = msp; - msp = (struct symbol *) calloc(1,sizeof(*msp)); - memset(msp, 0, sizeof(*msp)); - msp->type = MULTITERMINAL; - msp->nsubsym = 1; - msp->subsym = (struct symbol **) calloc(1,sizeof(struct symbol*)); - msp->subsym[0] = origsp; - msp->name = origsp->name; - psp->rhs[psp->nrhs-1] = msp; - } - msp->nsubsym++; - msp->subsym = (struct symbol **) realloc(msp->subsym, - sizeof(struct symbol*)*msp->nsubsym); - msp->subsym[msp->nsubsym-1] = Symbol_new(&x[1]); - if( islower(x[1]) || islower(msp->subsym[0]->name[0]) ){ - ErrorMsg(psp->filename,psp->tokenlineno, - "Cannot form a compound containing a non-terminal"); - psp->errorcnt++; - } - }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->decllinenoslot = 0; - psp->insertLineMacro = 1; - psp->state = WAITING_FOR_DECL_ARG; - if( strcmp(x,"name")==0 ){ - psp->declargslot = &(psp->gp->name); - psp->insertLineMacro = 0; - }else if( strcmp(x,"include")==0 ){ - psp->declargslot = &(psp->gp->include); - }else if( strcmp(x,"code")==0 ){ - psp->declargslot = &(psp->gp->extracode); - }else if( strcmp(x,"token_destructor")==0 ){ - psp->declargslot = &psp->gp->tokendest; - }else if( strcmp(x,"default_destructor")==0 ){ - psp->declargslot = &psp->gp->vardest; - }else if( strcmp(x,"token_prefix")==0 ){ - psp->declargslot = &psp->gp->tokenprefix; - psp->insertLineMacro = 0; - }else if( strcmp(x,"syntax_error")==0 ){ - psp->declargslot = &(psp->gp->error); - }else if( strcmp(x,"parse_accept")==0 ){ - psp->declargslot = &(psp->gp->accept); - }else if( strcmp(x,"parse_failure")==0 ){ - psp->declargslot = &(psp->gp->failure); - }else if( strcmp(x,"stack_overflow")==0 ){ - psp->declargslot = &(psp->gp->overflow); - }else if( strcmp(x,"extra_argument")==0 ){ - psp->declargslot = &(psp->gp->arg); - psp->insertLineMacro = 0; - }else if( strcmp(x,"token_type")==0 ){ - psp->declargslot = &(psp->gp->tokentype); - psp->insertLineMacro = 0; - }else if( strcmp(x,"default_type")==0 ){ - psp->declargslot = &(psp->gp->vartype); - psp->insertLineMacro = 0; - }else if( strcmp(x,"stack_size")==0 ){ - psp->declargslot = &(psp->gp->stacksize); - psp->insertLineMacro = 0; - }else if( strcmp(x,"start_symbol")==0 ){ - psp->declargslot = &(psp->gp->start); - psp->insertLineMacro = 0; - }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 if( strcmp(x,"wildcard")==0 ){ - psp->state = WAITING_FOR_WILDCARD_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->decllinenoslot = &sp->destLineno; - psp->insertLineMacro = 1; - 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 %%type keyword"); - psp->errorcnt++; - psp->state = RESYNC_AFTER_DECL_ERROR; - }else{ - struct symbol *sp = Symbol_find(x); - if((sp) && (sp->datatype)){ - ErrorMsg(psp->filename,psp->tokenlineno, - "Symbol %%type \"%s\" already defined", x); - psp->errorcnt++; - psp->state = RESYNC_AFTER_DECL_ERROR; - }else{ - if (!sp){ - sp = Symbol_new(x); - } - psp->declargslot = &sp->datatype; - psp->insertLineMacro = 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]) ){ - const char *zOld, *zNew; - char *zBuf, *z; - int nOld, n, nLine, nNew, nBack; - int addLineMacro; - char zLine[50]; - zNew = x; - if( zNew[0]=='"' || zNew[0]=='{' ) zNew++; - nNew = lemonStrlen(zNew); - if( *psp->declargslot ){ - zOld = *psp->declargslot; - }else{ - zOld = ""; - } - nOld = lemonStrlen(zOld); - n = nOld + nNew + 20; - addLineMacro = !psp->gp->nolinenosflag && psp->insertLineMacro && - (psp->decllinenoslot==0 || psp->decllinenoslot[0]!=0); - if( addLineMacro ){ - for(z=psp->filename, nBack=0; *z; z++){ - if( *z=='\\' ) nBack++; - } - sprintf(zLine, "#line %d ", psp->tokenlineno); - nLine = lemonStrlen(zLine); - n += nLine + lemonStrlen(psp->filename) + nBack; - } - *psp->declargslot = (char *) realloc(*psp->declargslot, n); - zBuf = *psp->declargslot + nOld; - if( addLineMacro ){ - if( nOld && zBuf[-1]!='\n' ){ - *(zBuf++) = '\n'; - } - memcpy(zBuf, zLine, nLine); - zBuf += nLine; - *(zBuf++) = '"'; - for(z=psp->filename; *z; z++){ - if( *z=='\\' ){ - *(zBuf++) = '\\'; - } - *(zBuf++) = *z; - } - *(zBuf++) = '"'; - *(zBuf++) = '\n'; - } - if( psp->decllinenoslot && psp->decllinenoslot[0]==0 ){ - psp->decllinenoslot[0] = psp->tokenlineno; - } - memcpy(zBuf, zNew, nNew); - zBuf += nNew; - *zBuf = 0; - 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 WAITING_FOR_WILDCARD_ID: - if( x[0]=='.' ){ - psp->state = WAITING_FOR_DECL_OR_RULE; - }else if( !isupper(x[0]) ){ - ErrorMsg(psp->filename, psp->tokenlineno, - "%%wildcard argument \"%s\" should be a token", x); - psp->errorcnt++; - }else{ - struct symbol *sp = Symbol_new(x); - if( psp->gp->wildcard==0 ){ - psp->gp->wildcard = sp; - }else{ - ErrorMsg(psp->filename, psp->tokenlineno, - "Extra wildcard to token: %s", x); - psp->errorcnt++; - } - } - 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 preprocessor 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 void preprocess_input(char *z){ - int i, j, k, n; - int exclude = 0; - int start = 0; - int lineno = 1; - int start_lineno = 1; - 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++; - fclose(fp); - 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++; - fclose(fp); - 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 if( (c=='/' || c=='|') && isalpha(cp[1]) ){ - cp += 2; - while( (c = *cp)!=0 && (isalnum(c) || c=='_') ) cp++; - 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 *newlink; - - if( plink_freelist==0 ){ - int i; - int amt = 100; - plink_freelist = (struct plink *)calloc( amt, sizeof(struct plink) ); - 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 newlink; -} - -/* Add a plink to a plink list */ -void Plink_add(struct plink **plpp, struct config *cfp) -{ - struct plink *newlink; - newlink = Plink_new(); - newlink->next = *plpp; - *plpp = newlink; - newlink->cfp = cfp; -} - -/* Transfer every plink on the list "from" to the list "to" */ -void Plink_copy(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(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(struct lemon *lemp, const char *suffix) -{ - char *name; - char *cp; - - name = (char*)malloc( lemonStrlen(lemp->filename) + lemonStrlen(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( - struct lemon *lemp, - const char *suffix, - const 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(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 = lemonStrlen(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++){ - sp = rp->rhs[i]; - printf(" %s", sp->name); - if( sp->type==MULTITERMINAL ){ - for(j=1; jnsubsym; j++){ - printf("|%s", sp->subsym[j]->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(FILE *fp, struct config *cfp) -{ - struct rule *rp; - struct symbol *sp; - int i, j; - 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; - sp = rp->rhs[i]; - fprintf(fp," %s", sp->name); - if( sp->type==MULTITERMINAL ){ - for(j=1; jnsubsym; j++){ - fprintf(fp,"|%s",sp->subsym[j]->name); - } - } - } -} - -/* #define TEST */ -#if 0 -/* 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->statenum); - 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->statenum); - 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 SRCONFLICT: - case RRCONFLICT: - fprintf(fp,"%*s reduce %-3d ** Parsing conflict **", - indent,ap->sp->name,ap->x.rp->index); - break; - case SSCONFLICT: - fprintf(fp,"%*s shift %-3d ** Parsing conflict **", - indent,ap->sp->name,ap->x.stp->statenum); - break; - case SH_RESOLVED: - if( showPrecedenceConflict ){ - fprintf(fp,"%*s shift %-3d -- dropped by precedence", - indent,ap->sp->name,ap->x.stp->statenum); - }else{ - result = 0; - } - break; - case RD_RESOLVED: - if( showPrecedenceConflict ){ - fprintf(fp,"%*s reduce %-3d -- dropped by precedence", - indent,ap->sp->name,ap->x.rp->index); - }else{ - result = 0; - } - break; - case NOT_USED: - result = 0; - break; - } - return result; -} - -/* Generate the "y.output" log file */ -void ReportOutput(struct lemon *lemp) -{ - int i; - struct state *stp; - struct config *cfp; - struct action *ap; - FILE *fp; - - fp = file_open(lemp,".out","wb"); - if( fp==0 ) return; - for(i=0; instate; i++){ - stp = lemp->sorted[i]; - fprintf(fp,"State %d:\n",stp->statenum); - 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"); -#if 0 - 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"); - } - fprintf(fp, "----------------------------------------------------\n"); - fprintf(fp, "Symbols:\n"); - for(i=0; insymbol; i++){ - int j; - struct symbol *sp; - - sp = lemp->symbols[i]; - fprintf(fp, " %3d: %s", i, sp->name); - if( sp->type==NONTERMINAL ){ - fprintf(fp, ":"); - if( sp->lambda ){ - fprintf(fp, " "); - } - for(j=0; jnterminal; j++){ - if( sp->firstset && SetFind(sp->firstset, j) ){ - fprintf(fp, " %s", lemp->symbols[j]->name); - } - } - } - fprintf(fp, "\n"); - } - fclose(fp); - return; -} - -/* Search for the file "name" which is in the same directory as -** the exacutable */ -PRIVATE char *pathsearch(char *argv0, char *name, int modemask) -{ - const char *pathlist; - char *pathbufptr; - char *pathbuf; - char *path,*cp; - char c; - -#ifdef __WIN32__ - cp = strrchr(argv0,'\\'); -#else - cp = strrchr(argv0,'/'); -#endif - if( cp ){ - c = *cp; - *cp = 0; - path = (char *)malloc( lemonStrlen(argv0) + lemonStrlen(name) + 2 ); - if( path ) sprintf(path,"%s/%s",argv0,name); - *cp = c; - }else{ - pathlist = getenv("PATH"); - if( pathlist==0 ) pathlist = ".:/bin:/usr/bin"; - pathbuf = (char *) malloc( lemonStrlen(pathlist) + 1 ); - path = (char *)malloc( lemonStrlen(pathlist)+lemonStrlen(name)+2 ); - if( (pathbuf != 0) && (path!=0) ){ - pathbufptr = pathbuf; - strcpy(pathbuf, pathlist); - while( *pathbuf ){ - cp = strchr(pathbuf,':'); - if( cp==0 ) cp = &pathbuf[lemonStrlen(pathbuf)]; - c = *cp; - *cp = 0; - sprintf(path,"%s/%s",pathbuf,name); - *cp = c; - if( c==0 ) pathbuf[0] = 0; - else pathbuf = &cp[1]; - if( access(path,modemask)==0 ) break; - } - free(pathbufptr); - } - } - 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(struct lemon *lemp, struct action *ap) -{ - int act; - switch( ap->type ){ - case SHIFT: act = ap->x.stp->statenum; 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(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(struct lemon *lemp) -{ - static char templatename[] = "lempar.c"; - char buf[1000]; - FILE *in; - char *tpltname; - char *cp; - - /* first, see if user specified a template filename on the command line. */ - if (user_templatename != 0) { - if( access(user_templatename,004)==-1 ){ - fprintf(stderr,"Can't find the parser driver template file \"%s\".\n", - user_templatename); - lemp->errorcnt++; - return 0; - } - in = fopen(user_templatename,"rb"); - if( in==0 ){ - fprintf(stderr,"Can't open the template file \"%s\".\n",user_templatename); - lemp->errorcnt++; - return 0; - } - return in; - } - - 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,"rb"); - if( in==0 ){ - fprintf(stderr,"Can't open the template file \"%s\".\n",templatename); - lemp->errorcnt++; - return 0; - } - return in; -} - -/* Print a #line directive line to the output file. */ -PRIVATE void tplt_linedir(FILE *out, int lineno, char *filename) -{ - fprintf(out,"#line %d \"",lineno); - while( *filename ){ - if( *filename == '\\' ) putc('\\',out); - putc(*filename,out); - filename++; - } - fprintf(out,"\"\n"); -} - -/* Print a string to the file and keep the linenumber up to date */ -PRIVATE void tplt_print(FILE *out, struct lemon *lemp, char *str, int *lineno) -{ - if( str==0 ) return; - while( *str ){ - putc(*str,out); - if( *str=='\n' ) (*lineno)++; - str++; - } - if( str[-1]!='\n' ){ - putc('\n',out); - (*lineno)++; - } - if (!lemp->nolinenosflag) { - (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); - } - return; -} - -/* -** The following routine emits code for the destructor for the -** symbol sp -*/ -void emit_destructor_code( - FILE *out, - struct symbol *sp, - struct lemon *lemp, - int *lineno -){ - char *cp = 0; - - if( sp->type==TERMINAL ){ - cp = lemp->tokendest; - if( cp==0 ) return; - fprintf(out,"{\n"); (*lineno)++; - }else if( sp->destructor ){ - cp = sp->destructor; - fprintf(out,"{\n"); (*lineno)++; - if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,sp->destLineno,lemp->filename); } - }else if( lemp->vardest ){ - cp = lemp->vardest; - if( cp==0 ) return; - fprintf(out,"{\n"); (*lineno)++; - }else{ - assert( 0 ); /* Cannot happen */ - } - for(; *cp; cp++){ - if( *cp=='$' && cp[1]=='$' ){ - fprintf(out,"(yypminor->yy%d)",sp->dtnum); - cp++; - continue; - } - if( *cp=='\n' ) (*lineno)++; - fputc(*cp,out); - } - fprintf(out,"\n"); (*lineno)++; - if (!lemp->nolinenosflag) { - (*lineno)++; tplt_linedir(out,*lineno,lemp->outname); - } - fprintf(out,"}\n"); (*lineno)++; - return; -} - -/* -** Return TRUE (non-zero) if the given symbol has a destructor. -*/ -int has_destructor(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(const char *zText, int n, int p1, int p2){ - static char empty[1] = { 0 }; - static char *z = 0; - static int alloced = 0; - static int used = 0; - int c; - char zInt[40]; - if( zText==0 ){ - used = 0; - return z; - } - if( n<=0 ){ - if( n<0 ){ - used += n; - assert( used>=0 ); - } - n = lemonStrlen(zText); - } - if( (int) (n+sizeof(zInt)*2+used) >= alloced ){ - alloced = n + sizeof(zInt)*2 + used + 200; - z = (char *) realloc(z, alloced); - } - if( z==0 ) return empty; - while( n-- > 0 ){ - c = *(zText++); - if( c=='%' && n>0 && zText[0]=='d' ){ - sprintf(zInt, "%d", p1); - p1 = p2; - strcpy(&z[used], zInt); - used += lemonStrlen(&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. -*/ -PRIVATE void 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; - - if( rp->code==0 ){ - static char newlinestr[2] = { '\n', '\0' }; - rp->code = newlinestr; - rp->line = rp->ruleline; - } - - append_str(0,0,0,0); - - /* This const cast is wrong but harmless, if we're careful. */ - for(cp=(char *)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{ - struct symbol *sp = rp->rhs[i]; - int dtnum; - if( sp->type==MULTITERMINAL ){ - dtnum = sp->subsym[0]->dtnum; - }else{ - dtnum = sp->dtnum; - } - append_str("yymsp[%d].minor.yy%d",0,i-rp->nrhs+1, 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(yypParser,%d,&yymsp[%d].minor);\n", 0, - rp->rhs[i]->index,i-rp->nrhs+1); - }else{ - /* No destructor defined for this term */ - } - } - } - if( rp->code ){ - cp = append_str(0,0,0,0); - rp->code = Strsafe(cp?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( - FILE *out, - struct rule *rp, - struct lemon *lemp, - int *lineno -){ - const char *cp; - - /* Generate code to do the reduce action */ - if( rp->code ){ - if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,rp->line,lemp->filename); } - fprintf(out,"{%s",rp->code); - for(cp=rp->code; *cp; cp++){ - if( *cp=='\n' ) (*lineno)++; - } /* End loop */ - fprintf(out,"}\n"); (*lineno)++; - if (!lemp->nolinenosflag) { (*lineno)++; tplt_linedir(out,*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( - 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 */ - unsigned hash; /* For hashing the name of a type */ - const char *name; /* Name of the parser */ - - /* Allocate and initialize types[] and allocate stddt[] */ - arraysize = lemp->nsymbol * 2; - types = (char**)calloc( arraysize, sizeof(char*) ); - if( types==0 ){ - fprintf(stderr,"Out of memory.\n"); - exit(1); - } - for(i=0; ivartype ){ - maxdtlength = lemonStrlen(lemp->vartype); - } - for(i=0; insymbol; i++){ - int len; - struct symbol *sp = lemp->symbols[i]; - if( sp->datatype==0 ) continue; - len = lemonStrlen(sp->datatype); - if( len>maxdtlength ) maxdtlength = len; - } - stddt = (char*)malloc( maxdtlength*2 + 1 ); - if( 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; - if( lemp->tokentype && strcmp(stddt, lemp->tokentype)==0 ){ - sp->dtnum = 0; - continue; - } - 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>=(unsigned)arraysize ) hash = 0; - } - if( types[hash]==0 ){ - sp->dtnum = hash + 1; - types[hash] = (char*)malloc( lemonStrlen(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," int yyinit;\n"); lineno++; - fprintf(out," %sTOKENTYPE yy0;\n",name); lineno++; - for(i=0; ierrsym->useCnt ){ - fprintf(out," int yy%d;\n",lemp->errsym->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 */ - int iOrder; /* Original order of action sets */ -}; - -/* -** 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; - int c; - c = p2->nAction - p1->nAction; - if( c==0 ){ - c = p2->iOrder - p1->iOrder; - } - assert( c!=0 || p1==p2 ); - return c; -} - -/* -** Write text on "out" that describes the rule "rp". -*/ -static void writeRuleText(FILE *out, struct rule *rp){ - int j; - fprintf(out,"%s ::=", rp->lhs->name); - for(j=0; jnrhs; j++){ - struct symbol *sp = rp->rhs[j]; - fprintf(out," %s", sp->name); - if( sp->type==MULTITERMINAL ){ - int k; - for(k=1; knsubsym; k++){ - fprintf(out,"|%s",sp->subsym[k]->name); - } - } - } -} - - -/* Generate C source code for the parser */ -void ReportTable( - 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; - const char *name; - int mnTknOfst, mxTknOfst; - int mnNtOfst, mxNtOfst; - struct axset *ax; - - in = tplt_open(lemp); - if( in==0 ) return; - out = file_open(lemp,".c","wb"); - 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,&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 ){ - const 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+1)); 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++; - if( lemp->wildcard ){ - fprintf(out,"#define YYWILDCARD %d\n", - lemp->wildcard->index); lineno++; - } - print_stack_union(out,lemp,&lineno,mhflag); - fprintf(out, "#ifndef YYSTACKDEPTH\n"); lineno++; - if( lemp->stacksize ){ - fprintf(out,"#define YYSTACKDEPTH %s\n",lemp->stacksize); lineno++; - }else{ - fprintf(out,"#define YYSTACKDEPTH 100\n"); lineno++; - } - fprintf(out, "#endif\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 = lemonStrlen(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++; - if( lemp->errsym->useCnt ){ - 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 = (struct axset *) calloc(lemp->nstate*2, sizeof(ax[0])); - if( ax==0 ){ - fprintf(stderr,"malloc failed\n"); - exit(1); - } - for(i=0; instate; i++){ - stp = lemp->sorted[i]; - 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. - */ - for(i=0; instate*2; i++) ax[i].iOrder = i; - 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 */ - n = acttab_size(pActtab); - fprintf(out,"#define YY_ACTTAB_COUNT (%d)\n", n); lineno++; - fprintf(out,"static const YYACTIONTYPE yy_action[] = {\n"); lineno++; - for(i=j=0; instate + 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 const 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++; - n = lemp->nstate; - while( n>0 && lemp->sorted[n-1]->iTknOfst==NO_OFFSET ) n--; - fprintf(out, "#define YY_SHIFT_COUNT (%d)\n", n-1); lineno++; - fprintf(out, "#define YY_SHIFT_MIN (%d)\n", mnTknOfst); lineno++; - fprintf(out, "#define YY_SHIFT_MAX (%d)\n", mxTknOfst); lineno++; - fprintf(out, "static const %s yy_shift_ofst[] = {\n", - minimum_size_type(mnTknOfst-1, mxTknOfst)); lineno++; - 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++; - n = lemp->nstate; - while( n>0 && lemp->sorted[n-1]->iNtOfst==NO_OFFSET ) n--; - fprintf(out, "#define YY_REDUCE_COUNT (%d)\n", n-1); lineno++; - fprintf(out, "#define YY_REDUCE_MIN (%d)\n", mnNtOfst); lineno++; - fprintf(out, "#define YY_REDUCE_MAX (%d)\n", mxNtOfst); lineno++; - fprintf(out, "static const %s yy_reduce_ofst[] = {\n", - minimum_size_type(mnNtOfst-1, mxNtOfst)); lineno++; - 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 const 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 ){ - int mx = lemp->nterminal - 1; - while( mx>0 && lemp->symbols[mx]->fallback==0 ){ mx--; } - for(i=0; i<=mx; 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 grammar. 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 */ \"", i); - writeRuleText(out, rp); - 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 ){ - int once = 1; - for(i=0; insymbol; i++){ - struct symbol *sp = lemp->symbols[i]; - if( sp==0 || sp->type!=TERMINAL ) continue; - if( once ){ - fprintf(out, " /* TERMINAL Destructor */\n"); lineno++; - once = 0; - } - fprintf(out," case %d: /* %s */\n", sp->index, sp->name); 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++; - } - } - if( lemp->vardest ){ - struct symbol *dflt_sp = 0; - int once = 1; - for(i=0; insymbol; i++){ - struct symbol *sp = lemp->symbols[i]; - if( sp==0 || sp->type==TERMINAL || - sp->index<=0 || sp->destructor!=0 ) continue; - if( once ){ - fprintf(out, " /* Default NON-TERMINAL Destructor */\n"); lineno++; - once = 0; - } - fprintf(out," case %d: /* %s */\n", sp->index, sp->name); lineno++; - dflt_sp = sp; - } - if( dflt_sp!=0 ){ - emit_destructor_code(out,dflt_sp,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: /* %s */\n", sp->index, sp->name); 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: /* %s */\n", - sp2->index, sp2->name); lineno++; - sp2->destructor = 0; - } - } - - emit_destructor_code(out,lemp->symbols[i],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,&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){ - translate_code(lemp, rp); - } - /* First output rules other than the default: rule */ - for(rp=lemp->rule; rp; rp=rp->next){ - struct rule *rp2; /* Other rules with the same action */ - if( rp->code==0 ) continue; - if( rp->code[0]=='\n' && rp->code[1]==0 ) continue; /* Will be default: */ - fprintf(out," case %d: /* ", rp->index); - writeRuleText(out, rp); - fprintf(out, " */\n"); lineno++; - for(rp2=rp->next; rp2; rp2=rp2->next){ - if( rp2->code==rp->code ){ - fprintf(out," case %d: /* ", rp2->index); - writeRuleText(out, rp2); - fprintf(out," */ yytestcase(yyruleno==%d);\n", rp2->index); lineno++; - rp2->code = 0; - } - } - emit_code(out,rp,lemp,&lineno); - fprintf(out," break;\n"); lineno++; - rp->code = 0; - } - /* Finally, output the default: rule. We choose as the default: all - ** empty actions. */ - fprintf(out," default:\n"); lineno++; - for(rp=lemp->rule; rp; rp=rp->next){ - if( rp->code==0 ) continue; - assert( rp->code[0]=='\n' && rp->code[1]==0 ); - fprintf(out," /* (%d) ", rp->index); - writeRuleText(out, rp); - fprintf(out, " */ yytestcase(yyruleno==%d);\n", rp->index); 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,&lineno); - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate code which executes when a syntax error occurs */ - tplt_print(out,lemp,lemp->error,&lineno); - tplt_xfer(lemp->name,in,out,&lineno); - - /* Generate code which executes when the parser accepts its input */ - tplt_print(out,lemp,lemp->accept,&lineno); - tplt_xfer(lemp->name,in,out,&lineno); - - /* Append any addition code the user desires */ - tplt_print(out,lemp,lemp->extracode,&lineno); - - fclose(in); - fclose(out); - return; -} - -/* Generate a header file for the parser */ -void ReportHeader(struct lemon *lemp) -{ - FILE *out, *in; - const char *prefix; - char line[LINESIZE]; - char pattern[LINESIZE]; - int i; - - if( lemp->tokenprefix ) prefix = lemp->tokenprefix; - else prefix = ""; - in = file_open(lemp,".h","rb"); - if( in ){ - int nextChar; - 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; - } - nextChar = fgetc(in); - fclose(in); - if( i==lemp->nterminal && nextChar==EOF ){ - /* No change in the file. Don't rewrite it. */ - return; - } - } - out = file_open(lemp,".h","wb"); - 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. Except, there is no default if the wildcard token -** is a possible look-ahead. -*/ -void CompressTables(struct lemon *lemp) -{ - struct state *stp; - struct action *ap, *ap2; - struct rule *rp, *rp2, *rbest; - int nbest, n; - int i; - int usesWildcard; - - for(i=0; instate; i++){ - stp = lemp->sorted[i]; - nbest = 0; - rbest = 0; - usesWildcard = 0; - - for(ap=stp->ap; ap; ap=ap->next){ - if( ap->type==SHIFT && ap->sp==lemp->wildcard ){ - usesWildcard = 1; - } - if( ap->type!=REDUCE ) continue; - rp = ap->x.rp; - if( rp->lhsStart ) continue; - 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 1 or if the wildcard token is a possible - ** lookahead. - */ - if( nbest<1 || usesWildcard ) 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); - } -} - - -/* -** Compare two states for sorting purposes. The smaller state is the -** one with the most non-terminal actions. If they have the same number -** of non-terminal actions, then the smaller is the one with the most -** token actions. -*/ -static int stateResortCompare(const void *a, const void *b){ - const struct state *pA = *(const struct state**)a; - const struct state *pB = *(const struct state**)b; - int n; - - n = pB->nNtAct - pA->nNtAct; - if( n==0 ){ - n = pB->nTknAct - pA->nTknAct; - if( n==0 ){ - n = pB->statenum - pA->statenum; - } - } - assert( n!=0 ); - return n; -} - - -/* -** Renumber and resort states so that states with fewer choices -** occur at the end. Except, keep state 0 as the first state. -*/ -void ResortStates(struct lemon *lemp) -{ - int i; - struct state *stp; - struct action *ap; - - 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); - } - } - } - } - qsort(&lemp->sorted[1], lemp->nstate-1, sizeof(lemp->sorted[0]), - stateResortCompare); - for(i=0; instate; i++){ - lemp->sorted[i]->statenum = i; - } -} - - -/***************** From the file "set.c" ************************************/ -/* -** Set manipulation routines for the LEMON parser generator. -*/ - -static int size = 0; - -/* Set the set size */ -void SetSize(int n) -{ - size = n+1; -} - -/* Allocate a new set */ -char *SetNew(){ - char *s; - s = (char*)calloc( size, 1); - if( s==0 ){ - extern void memory_error(); - memory_error(); - } - return s; -} - -/* Deallocate a set */ -void SetFree(char *s) -{ - free(s); -} - -/* Add a new element to the set. Return TRUE if the element was added -** and FALSE if it was already there. */ -int SetAdd(char *s, int e) -{ - int rv; - assert( e>=0 && esize = 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(const char *data) -{ - x1node *np; - unsigned h; - unsigned 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. */ -const char *Strsafe_find(const char *key) -{ - unsigned 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(const char *x) -{ - struct symbol *sp; - - sp = Symbol_find(x); - if( sp==0 ){ - sp = (struct symbol *)calloc(1, 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 = LEMON_FALSE; - sp->destructor = 0; - sp->destLineno = 0; - sp->datatype = 0; - sp->useCnt = 0; - Symbol_insert(sp,sp->name); - } - sp->useCnt++; - 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(const void *_a, const void *_b) -{ - const struct symbol **a = (const struct symbol **) _a; - const struct symbol **b = (const struct symbol **) _b; - int i1 = (**a).index + 10000000*((**a).name[0]>'Z'); - int i2 = (**b).index + 10000000*((**b).name[0]>'Z'); - assert( i1!=i2 || strcmp((**a).name,(**b).name)==0 ); - 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 */ - const 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(struct symbol *data, const char *key) -{ - x2node *np; - unsigned h; - unsigned 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(const char *key) -{ - unsigned 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(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 **)calloc(size, sizeof(struct symbol *)); - if( array ){ - for(i=0; itbl[i].data; - } - return array; -} - -/* Compare two configurations */ -int Configcmp(const char *_a,const char *_b) -{ - const struct config *a = (struct config *) _a; - const struct config *b = (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(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 unsigned statehash(struct config *a) -{ - unsigned 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 *newstate; - newstate = (struct state *)calloc(1, sizeof(struct state) ); - MemoryCheck(newstate); - return newstate; -} - -/* 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(struct state *data, struct config *key) -{ - x3node *np; - unsigned h; - unsigned 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(struct config *key) -{ - unsigned 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 unsigned confighash(struct config *a) -{ - unsigned 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(struct config *data) -{ - x4node *np; - unsigned h; - unsigned ph; - - if( x4a==0 ) return 0; - ph = confighash(data); - h = ph & (x4a->size-1); - np = x4a->ht[h]; - while( np ){ - if( Configcmp((const char *) np->data,(const char *) 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(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((const char *) np->data,(const char *) 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(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; -} diff --git a/components/external/SQLite-3.8.1/tool/lempar.c b/components/external/SQLite-3.8.1/tool/lempar.c deleted file mode 100644 index fe56d2dc16..0000000000 --- a/components/external/SQLite-3.8.1/tool/lempar.c +++ /dev/null @@ -1,850 +0,0 @@ -/* Driver template for the LEMON parser generator. -** The author disclaims copyright to this source code. -*/ -/* First off, code is included that follows the "include" declaration -** in the input grammar 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. If -** zero the stack is dynamically sized using realloc() -** 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) - -/* The yyzerominor constant is used to initialize instances of -** YYMINORTYPE objects to zero. */ -static const YYMINORTYPE yyzerominor = { 0 }; - -/* Define the yytestcase() macro to be a no-op if is not already defined -** otherwise. -** -** Applications can choose to define yytestcase() in the %include section -** to a macro that can assist in verifying code coverage. For production -** code the yytestcase() macro should be turned off. But it is useful -** for testing. -*/ -#ifndef yytestcase -# define yytestcase(X) -#endif - - -/* Next are the 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. -*/ -%% - -/* The next table maps tokens into fallback tokens. If a construct -** like the following: -** -** %fallback ID X Y Z. -** -** appears in the grammar, 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 { - YYACTIONTYPE stateno; /* The state-number */ - YYCODETYPE 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 */ -#ifdef YYTRACKMAXSTACKDEPTH - int yyidxMax; /* Maximum value of yyidx */ -#endif - int yyerrcnt; /* Shifts left before out of the error */ - ParseARG_SDECL /* A place to hold %extra_argument */ -#if YYSTACKDEPTH<=0 - int yystksz; /* Current side of the stack */ - yyStackEntry *yystack; /* The parser's stack */ -#else - yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ -#endif -}; -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 *const yyTokenName[] = { -%% -}; -#endif /* NDEBUG */ - -#ifndef NDEBUG -/* For tracing reduce actions, the names of all rules are required. -*/ -static const char *const yyRuleName[] = { -%% -}; -#endif /* NDEBUG */ - - -#if YYSTACKDEPTH<=0 -/* -** Try to increase the size of the parser stack. -*/ -static void yyGrowStack(yyParser *p){ - int newSize; - yyStackEntry *pNew; - - newSize = p->yystksz*2 + 100; - pNew = realloc(p->yystack, newSize*sizeof(pNew[0])); - if( pNew ){ - p->yystack = pNew; - p->yystksz = newSize; -#ifndef NDEBUG - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sStack grows to %d entries!\n", - yyTracePrompt, p->yystksz); - } -#endif - } -} -#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; -#ifdef YYTRACKMAXSTACKDEPTH - pParser->yyidxMax = 0; -#endif -#if YYSTACKDEPTH<=0 - pParser->yystack = NULL; - pParser->yystksz = 0; - yyGrowStack(pParser); -#endif - } - 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( - yyParser *yypParser, /* The parser */ - YYCODETYPE yymajor, /* Type code for object to destroy */ - YYMINORTYPE *yypminor /* The object to be destroyed */ -){ - ParseARG_FETCH; - 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(pParser, 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); -#if YYSTACKDEPTH<=0 - free(pParser->yystack); -#endif - (*freeProc)((void*)pParser); -} - -/* -** Return the peak depth of the stack for a parser. -*/ -#ifdef YYTRACKMAXSTACKDEPTH -int ParseStackPeak(void *p){ - yyParser *pParser = (yyParser*)p; - return pParser->yyidxMax; -} -#endif - -/* -** 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 */ - YYCODETYPE iLookAhead /* The look-ahead token */ -){ - int i; - int stateno = pParser->yystack[pParser->yyidx].stateno; - - if( stateno>YY_SHIFT_COUNT - || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){ - return yy_default[stateno]; - } - assert( iLookAhead!=YYNOCODE ); - i += iLookAhead; - if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ - if( iLookAhead>0 ){ -#ifdef YYFALLBACK - YYCODETYPE iFallback; /* Fallback token */ - if( iLookAhead %s\n", - yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); - } -#endif - return yy_find_shift_action(pParser, iFallback); - } -#endif -#ifdef YYWILDCARD - { - int j = i - iLookAhead + YYWILDCARD; - if( -#if YY_SHIFT_MIN+YYWILDCARD<0 - j>=0 && -#endif -#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT - j %s\n", - yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]); - } -#endif /* NDEBUG */ - return yy_action[j]; - } - } -#endif /* YYWILDCARD */ - } - 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( - int stateno, /* Current state number */ - YYCODETYPE iLookAhead /* The look-ahead token */ -){ - int i; -#ifdef YYERRORSYMBOL - if( stateno>YY_REDUCE_COUNT ){ - return yy_default[stateno]; - } -#else - assert( stateno<=YY_REDUCE_COUNT ); -#endif - i = yy_reduce_ofst[stateno]; - assert( i!=YY_REDUCE_USE_DFLT ); - assert( iLookAhead!=YYNOCODE ); - i += iLookAhead; -#ifdef YYERRORSYMBOL - if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ - return yy_default[stateno]; - } -#else - assert( i>=0 && iyyidx--; -#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 */ -} - -/* -** 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 to the minor token to shift in */ -){ - yyStackEntry *yytos; - yypParser->yyidx++; -#ifdef YYTRACKMAXSTACKDEPTH - if( yypParser->yyidx>yypParser->yyidxMax ){ - yypParser->yyidxMax = yypParser->yyidx; - } -#endif -#if YYSTACKDEPTH>0 - if( yypParser->yyidx>=YYSTACKDEPTH ){ - yyStackOverflow(yypParser, yypMinor); - return; - } -#else - if( yypParser->yyidx>=yypParser->yystksz ){ - yyGrowStack(yypParser); - if( yypParser->yyidx>=yypParser->yystksz ){ - yyStackOverflow(yypParser, yypMinor); - return; - } - } -#endif - yytos = &yypParser->yystack[yypParser->yyidx]; - yytos->stateno = (YYACTIONTYPE)yyNewState; - yytos->major = (YYCODETYPE)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 const 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<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ - fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, - yyRuleName[yyruleno]); - } -#endif /* NDEBUG */ - - /* Silence complaints from purify about yygotominor being uninitialized - ** in some cases when it is copied into the stack after the following - ** switch. yygotominor is uninitialized when a rule reduces that does - ** not set the value of its left-hand side nonterminal. Leaving the - ** value of the nonterminal uninitialized is utterly harmless as long - ** as the value is never used. So really the only thing this code - ** accomplishes is to quieten purify. - ** - ** 2007-01-16: The wireshark project (www.wireshark.org) reports that - ** without this code, their parser segfaults. I'm not sure what there - ** parser is doing to make this happen. This is the second bug report - ** from wireshark this week. Clearly they are stressing Lemon in ways - ** that it has not been previously stressed... (SQLite ticket #2172) - */ - /*memset(&yygotominor, 0, sizeof(yygotominor));*/ - yygotominor = yyzerominor; - - - switch( yyruleno ){ - /* Beginning here are the reduction cases. A typical example - ** follows: - ** case 0: - ** #line - ** { ... } // User supplied code - ** #line - ** break; - */ -%% - }; - yygoto = yyRuleInfo[yyruleno].lhs; - yysize = yyRuleInfo[yyruleno].nrhs; - yypParser->yyidx -= yysize; - yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto); - if( yyact < YYNSTATE ){ -#ifdef NDEBUG - /* If we are not debugging and the reduce action popped at least - ** one element off the stack, then we can push the new element back - ** onto the stack here, and skip the stack overflow test in yy_shift(). - ** That gives a significant speed improvement. */ - if( yysize ){ - yypParser->yyidx++; - yymsp -= yysize-1; - yymsp->stateno = (YYACTIONTYPE)yyact; - yymsp->major = (YYCODETYPE)yygoto; - yymsp->minor = yygotominor; - }else -#endif - { - yy_shift(yypParser,yyact,yygoto,&yygotominor); - } - }else{ - assert( yyact == YYNSTATE + YYNRULE + 1 ); - yy_accept(yypParser); - } -} - -/* -** The following code executes when the parse fails -*/ -#ifndef YYNOERRORRECOVERY -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 */ -} -#endif /* YYNOERRORRECOVERY */ - -/* -** 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 */ -#ifdef YYERRORSYMBOL - int yyerrorhit = 0; /* True if yymajor has invoked an error */ -#endif - yyParser *yypParser; /* The parser */ - - /* (re)initialize the parser, if necessary */ - yypParser = (yyParser*)yyp; - if( yypParser->yyidx<0 ){ -#if YYSTACKDEPTH<=0 - if( yypParser->yystksz <=0 ){ - /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/ - yyminorunion = yyzerominor; - yyStackOverflow(yypParser, &yyminorunion); - return; - } -#endif - 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,(YYCODETYPE)yymajor); - if( yyactyyerrcnt--; - yymajor = YYNOCODE; - }else if( yyact < YYNSTATE + YYNRULE ){ - yy_reduce(yypParser,yyact-YYNSTATE); - }else{ - assert( yyact == YY_ERROR_ACTION ); -#ifdef YYERRORSYMBOL - int yymx; -#endif -#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(yypParser, (YYCODETYPE)yymajor,&yyminorunion); - yymajor = YYNOCODE; - }else{ - while( - yypParser->yyidx >= 0 && - yymx != YYERRORSYMBOL && - (yyact = yy_find_reduce_action( - yypParser->yystack[yypParser->yyidx].stateno, - YYERRORSYMBOL)) >= YYNSTATE - ){ - yy_pop_parser_stack(yypParser); - } - if( yypParser->yyidx < 0 || yymajor==0 ){ - yy_destructor(yypParser,(YYCODETYPE)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; -#elif defined(YYNOERRORRECOVERY) - /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to - ** do any kind of error recovery. Instead, simply invoke the syntax - ** error routine and continue going as if nothing had happened. - ** - ** Applications can set this macro (for example inside %include) if - ** they intend to abandon the parse upon the first syntax error seen. - */ - yy_syntax_error(yypParser,yymajor,yyminorunion); - yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); - yymajor = YYNOCODE; - -#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(yypParser,(YYCODETYPE)yymajor,&yyminorunion); - if( yyendofinput ){ - yy_parse_failed(yypParser); - } - yymajor = YYNOCODE; -#endif - } - }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); - return; -} diff --git a/components/external/SQLite-3.8.1/tool/logest.c b/components/external/SQLite-3.8.1/tool/logest.c deleted file mode 100644 index 8dad6cc9b6..0000000000 --- a/components/external/SQLite-3.8.1/tool/logest.c +++ /dev/null @@ -1,141 +0,0 @@ -/* -** 2013-06-10 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains a simple command-line utility for converting from -** integers and LogEst values and back again and for doing simple -** arithmetic operations (multiple and add) on LogEst values. -** -** Usage: -** -** ./LogEst ARGS -** -** Arguments: -** -** 'x' Multiple the top two elements of the stack -** '+' Add the top two elements of the stack -** NUM Convert NUM from integer to LogEst and push onto the stack -** ^NUM Interpret NUM as a LogEst and push onto stack. -** -** Examples: -** -** To convert 123 from LogEst to integer: -** -** ./LogEst ^123 -** -** To convert 123456 from integer to LogEst: -** -** ./LogEst 123456 -** -*/ -#include -#include -#include -#include -#include -#include "sqlite3.h" - -typedef short int LogEst; /* 10 times log2() */ - -LogEst logEstMultiply(LogEst a, LogEst b){ return a+b; } -LogEst logEstAdd(LogEst a, LogEst b){ - static const unsigned char x[] = { - 10, 10, /* 0,1 */ - 9, 9, /* 2,3 */ - 8, 8, /* 4,5 */ - 7, 7, 7, /* 6,7,8 */ - 6, 6, 6, /* 9,10,11 */ - 5, 5, 5, /* 12-14 */ - 4, 4, 4, 4, /* 15-18 */ - 3, 3, 3, 3, 3, 3, /* 19-24 */ - 2, 2, 2, 2, 2, 2, 2, /* 25-31 */ - }; - if( ab+49 ) return a; - if( a>b+31 ) return a+1; - return a+x[a-b]; -} -LogEst logEstFromInteger(sqlite3_uint64 x){ - static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 }; - LogEst y = 40; - if( x<8 ){ - if( x<2 ) return 0; - while( x<8 ){ y -= 10; x <<= 1; } - }else{ - while( x>255 ){ y += 40; x >>= 4; } - while( x>15 ){ y += 10; x >>= 1; } - } - return a[x&7] + y - 10; -} -static sqlite3_uint64 logEstToInt(LogEst x){ - sqlite3_uint64 n; - if( x<10 ) return 1; - n = x%10; - x /= 10; - if( n>=5 ) n -= 2; - else if( n>=1 ) n -= 1; - if( x>=3 ) return (n+8)<<(x-3); - return (n+8)>>(3-x); -} -static LogEst logEstFromDouble(double x){ - sqlite3_uint64 a; - LogEst e; - assert( sizeof(x)==8 && sizeof(a)==8 ); - if( x<=0.0 ) return -32768; - if( x<1.0 ) return -logEstFromDouble(1/x); - if( x<1024.0 ) return logEstFromInteger((sqlite3_uint64)(1024.0*x)) - 100; - if( x<=2000000000.0 ) return logEstFromInteger((sqlite3_uint64)x); - memcpy(&a, &x, 8); - e = (a>>52) - 1022; - return e*10; -} - -int isFloat(const char *z){ - while( z[0] ){ - if( z[0]=='.' || z[0]=='E' || z[0]=='e' ) return 1; - z++; - } - return 0; -} - -int main(int argc, char **argv){ - int i; - int n = 0; - LogEst a[100]; - for(i=1; i=2 ){ - a[n-2] = logEstAdd(a[n-2],a[n-1]); - n--; - } - }else if( z[0]=='x' ){ - if( n>=2 ){ - a[n-2] = logEstMultiply(a[n-2],a[n-1]); - n--; - } - }else if( z[0]=='^' ){ - a[n++] = atoi(z+1); - }else if( isFloat(z) ){ - a[n++] = logEstFromDouble(atof(z)); - }else{ - a[n++] = logEstFromInteger(atoi(z)); - } - } - for(i=n-1; i>=0; i--){ - if( a[i]<0 ){ - printf("%d (%f)\n", a[i], 1.0/(double)logEstToInt(-a[i])); - }else{ - sqlite3_uint64 x = logEstToInt(a[i]+100)*100/1024; - printf("%d (%lld.%02lld)\n", a[i], x/100, x%100); - } - } - return 0; -} diff --git a/components/external/SQLite-3.8.1/tool/mkautoconfamal.sh b/components/external/SQLite-3.8.1/tool/mkautoconfamal.sh deleted file mode 100644 index c13f7c999a..0000000000 --- a/components/external/SQLite-3.8.1/tool/mkautoconfamal.sh +++ /dev/null @@ -1,83 +0,0 @@ -#!/bin/sh -# This script is used to build the amalgamation autoconf package. -# It assumes the following: -# -# 1. The files "sqlite3.c", "sqlite3.h" and "sqlite3ext.h" -# are available in the current directory. -# -# 2. Variable $TOP is set to the full path of the root directory -# of the SQLite source tree. -# -# 3. There is nothing of value in the ./mkpkg_tmp_dir directory. -# This is important, as the script executes "rm -rf ./mkpkg_tmp_dir". -# - - -# Bail out of the script if any command returns a non-zero exit -# status. Or if the script tries to use an unset variable. These -# may fail for old /bin/sh interpreters. -# -set -e -set -u - -TMPSPACE=./mkpkg_tmp_dir -VERSION=`cat $TOP/VERSION` - -# Set global variable $ARTIFACT to the "3xxyyzz" string incorporated -# into artifact filenames. And $VERSION2 to the "3.x.y[.z]" form. -xx=`echo $VERSION|sed 's/3\.\([0-9]*\)\..*/\1/'` -yy=`echo $VERSION|sed 's/3\.[^.]*\.\([0-9]*\).*/\1/'` -zz=0 -set +e - zz=`echo $VERSION|sed 's/3\.[^.]*\.[^.]*\.\([0-9]*\).*/\1/'|grep -v '\.'` -set -e -ARTIFACT=`printf "3%.2d%.2d%.2d" $xx $yy $zz` - -rm -rf $TMPSPACE -cp -R $TOP/autoconf $TMPSPACE - -cp sqlite3.c $TMPSPACE -cp sqlite3.h $TMPSPACE -cp sqlite3ext.h $TMPSPACE -cp $TOP/sqlite3.1 $TMPSPACE -cp $TOP/sqlite3.pc.in $TMPSPACE -cp $TOP/src/shell.c $TMPSPACE - -chmod 755 $TMPSPACE/install-sh -chmod 755 $TMPSPACE/missing -chmod 755 $TMPSPACE/depcomp -chmod 755 $TMPSPACE/config.sub -chmod 755 $TMPSPACE/config.guess - -cat $TMPSPACE/configure.ac | -sed "s/AC_INIT(sqlite, .*, http:\/\/www.sqlite.org)/AC_INIT(sqlite, $VERSION, http:\/\/www.sqlite.org)/" > $TMPSPACE/tmp -mv $TMPSPACE/tmp $TMPSPACE/configure.ac - -cd $TMPSPACE -aclocal -autoconf -automake - -mkdir -p tea/generic -echo "#ifdef USE_SYSTEM_SQLITE" > tea/generic/tclsqlite3.c -echo "# include " >> tea/generic/tclsqlite3.c -echo "#else" >> tea/generic/tclsqlite3.c -echo "#include \"../../sqlite3.c\"" >> tea/generic/tclsqlite3.c -echo "#endif" >> tea/generic/tclsqlite3.c -cat $TOP/src/tclsqlite.c >> tea/generic/tclsqlite3.c - -cat tea/configure.in | - sed "s/AC_INIT(\[sqlite\], .*)/AC_INIT([sqlite], [$VERSION])/" > tmp -mv tmp tea/configure.in - -cd tea -autoconf -rm -rf autom4te.cache - -cd ../ -./configure && make dist -tar -xzf sqlite-$VERSION.tar.gz -mv sqlite-$VERSION sqlite-autoconf-$ARTIFACT -tar -czf sqlite-autoconf-$ARTIFACT.tar.gz sqlite-autoconf-$ARTIFACT -mv sqlite-autoconf-$ARTIFACT.tar.gz .. - diff --git a/components/external/SQLite-3.8.1/tool/mkkeywordhash.c b/components/external/SQLite-3.8.1/tool/mkkeywordhash.c deleted file mode 100644 index 4e5ba8f1a8..0000000000 --- a/components/external/SQLite-3.8.1/tool/mkkeywordhash.c +++ /dev/null @@ -1,602 +0,0 @@ -/* -** Compile and run this standalone program in order to generate code that -** implements a function that will translate alphabetic identifiers into -** parser token codes. -*/ -#include -#include -#include -#include - -/* -** A header comment placed at the beginning of generated code. -*/ -static const char zHdr[] = - "/***** This file contains automatically generated code ******\n" - "**\n" - "** The code in this file has been automatically generated by\n" - "**\n" - "** sqlite/tool/mkkeywordhash.c\n" - "**\n" - "** The code in this file implements a function that determines whether\n" - "** or not a given identifier is really an SQL keyword. The same thing\n" - "** might be implemented more directly using a hand-written hash table.\n" - "** But by using this automatically generated code, the size of the code\n" - "** is substantially reduced. This is important for embedded applications\n" - "** on platforms with limited memory.\n" - "*/\n" -; - -/* -** All the keywords of the SQL language are stored in a hash -** table composed of instances of the following structure. -*/ -typedef struct Keyword Keyword; -struct Keyword { - char *zName; /* The keyword name */ - char *zTokenType; /* Token value for this keyword */ - int mask; /* Code this keyword if non-zero */ - int id; /* Unique ID for this record */ - int hash; /* Hash on the keyword */ - int offset; /* Offset to start of name string */ - int len; /* Length of this keyword, not counting final \000 */ - int prefix; /* Number of characters in prefix */ - int longestSuffix; /* Longest suffix that is a prefix on another word */ - int iNext; /* Index in aKeywordTable[] of next with same hash */ - int substrId; /* Id to another keyword this keyword is embedded in */ - int substrOffset; /* Offset into substrId for start of this keyword */ - char zOrigName[20]; /* Original keyword name before processing */ -}; - -/* -** Define masks used to determine which keywords are allowed -*/ -#ifdef SQLITE_OMIT_ALTERTABLE -# define ALTER 0 -#else -# define ALTER 0x00000001 -#endif -#define ALWAYS 0x00000002 -#ifdef SQLITE_OMIT_ANALYZE -# define ANALYZE 0 -#else -# define ANALYZE 0x00000004 -#endif -#ifdef SQLITE_OMIT_ATTACH -# define ATTACH 0 -#else -# define ATTACH 0x00000008 -#endif -#ifdef SQLITE_OMIT_AUTOINCREMENT -# define AUTOINCR 0 -#else -# define AUTOINCR 0x00000010 -#endif -#ifdef SQLITE_OMIT_CAST -# define CAST 0 -#else -# define CAST 0x00000020 -#endif -#ifdef SQLITE_OMIT_COMPOUND_SELECT -# define COMPOUND 0 -#else -# define COMPOUND 0x00000040 -#endif -#ifdef SQLITE_OMIT_CONFLICT_CLAUSE -# define CONFLICT 0 -#else -# define CONFLICT 0x00000080 -#endif -#ifdef SQLITE_OMIT_EXPLAIN -# define EXPLAIN 0 -#else -# define EXPLAIN 0x00000100 -#endif -#ifdef SQLITE_OMIT_FOREIGN_KEY -# define FKEY 0 -#else -# define FKEY 0x00000200 -#endif -#ifdef SQLITE_OMIT_PRAGMA -# define PRAGMA 0 -#else -# define PRAGMA 0x00000400 -#endif -#ifdef SQLITE_OMIT_REINDEX -# define REINDEX 0 -#else -# define REINDEX 0x00000800 -#endif -#ifdef SQLITE_OMIT_SUBQUERY -# define SUBQUERY 0 -#else -# define SUBQUERY 0x00001000 -#endif -#ifdef SQLITE_OMIT_TRIGGER -# define TRIGGER 0 -#else -# define TRIGGER 0x00002000 -#endif -#if defined(SQLITE_OMIT_AUTOVACUUM) && \ - (defined(SQLITE_OMIT_VACUUM) || defined(SQLITE_OMIT_ATTACH)) -# define VACUUM 0 -#else -# define VACUUM 0x00004000 -#endif -#ifdef SQLITE_OMIT_VIEW -# define VIEW 0 -#else -# define VIEW 0x00008000 -#endif -#ifdef SQLITE_OMIT_VIRTUALTABLE -# define VTAB 0 -#else -# define VTAB 0x00010000 -#endif -#ifdef SQLITE_OMIT_AUTOVACUUM -# define AUTOVACUUM 0 -#else -# define AUTOVACUUM 0x00020000 -#endif - -/* -** These are the keywords -*/ -static Keyword aKeywordTable[] = { - { "ABORT", "TK_ABORT", CONFLICT|TRIGGER }, - { "ACTION", "TK_ACTION", FKEY }, - { "ADD", "TK_ADD", ALTER }, - { "AFTER", "TK_AFTER", TRIGGER }, - { "ALL", "TK_ALL", ALWAYS }, - { "ALTER", "TK_ALTER", ALTER }, - { "ANALYZE", "TK_ANALYZE", ANALYZE }, - { "AND", "TK_AND", ALWAYS }, - { "AS", "TK_AS", ALWAYS }, - { "ASC", "TK_ASC", ALWAYS }, - { "ATTACH", "TK_ATTACH", ATTACH }, - { "AUTOINCREMENT", "TK_AUTOINCR", AUTOINCR }, - { "BEFORE", "TK_BEFORE", TRIGGER }, - { "BEGIN", "TK_BEGIN", ALWAYS }, - { "BETWEEN", "TK_BETWEEN", ALWAYS }, - { "BY", "TK_BY", ALWAYS }, - { "CASCADE", "TK_CASCADE", FKEY }, - { "CASE", "TK_CASE", ALWAYS }, - { "CAST", "TK_CAST", CAST }, - { "CHECK", "TK_CHECK", ALWAYS }, - { "COLLATE", "TK_COLLATE", ALWAYS }, - { "COLUMN", "TK_COLUMNKW", ALTER }, - { "COMMIT", "TK_COMMIT", ALWAYS }, - { "CONFLICT", "TK_CONFLICT", CONFLICT }, - { "CONSTRAINT", "TK_CONSTRAINT", ALWAYS }, - { "CREATE", "TK_CREATE", ALWAYS }, - { "CROSS", "TK_JOIN_KW", ALWAYS }, - { "CURRENT_DATE", "TK_CTIME_KW", ALWAYS }, - { "CURRENT_TIME", "TK_CTIME_KW", ALWAYS }, - { "CURRENT_TIMESTAMP","TK_CTIME_KW", ALWAYS }, - { "DATABASE", "TK_DATABASE", ATTACH }, - { "DEFAULT", "TK_DEFAULT", ALWAYS }, - { "DEFERRED", "TK_DEFERRED", ALWAYS }, - { "DEFERRABLE", "TK_DEFERRABLE", FKEY }, - { "DELETE", "TK_DELETE", ALWAYS }, - { "DESC", "TK_DESC", ALWAYS }, - { "DETACH", "TK_DETACH", ATTACH }, - { "DISTINCT", "TK_DISTINCT", ALWAYS }, - { "DROP", "TK_DROP", ALWAYS }, - { "END", "TK_END", ALWAYS }, - { "EACH", "TK_EACH", TRIGGER }, - { "ELSE", "TK_ELSE", ALWAYS }, - { "ESCAPE", "TK_ESCAPE", ALWAYS }, - { "EXCEPT", "TK_EXCEPT", COMPOUND }, - { "EXCLUSIVE", "TK_EXCLUSIVE", ALWAYS }, - { "EXISTS", "TK_EXISTS", ALWAYS }, - { "EXPLAIN", "TK_EXPLAIN", EXPLAIN }, - { "FAIL", "TK_FAIL", CONFLICT|TRIGGER }, - { "FOR", "TK_FOR", TRIGGER }, - { "FOREIGN", "TK_FOREIGN", FKEY }, - { "FROM", "TK_FROM", ALWAYS }, - { "FULL", "TK_JOIN_KW", ALWAYS }, - { "GLOB", "TK_LIKE_KW", ALWAYS }, - { "GROUP", "TK_GROUP", ALWAYS }, - { "HAVING", "TK_HAVING", ALWAYS }, - { "IF", "TK_IF", ALWAYS }, - { "IGNORE", "TK_IGNORE", CONFLICT|TRIGGER }, - { "IMMEDIATE", "TK_IMMEDIATE", ALWAYS }, - { "IN", "TK_IN", ALWAYS }, - { "INDEX", "TK_INDEX", ALWAYS }, - { "INDEXED", "TK_INDEXED", ALWAYS }, - { "INITIALLY", "TK_INITIALLY", FKEY }, - { "INNER", "TK_JOIN_KW", ALWAYS }, - { "INSERT", "TK_INSERT", ALWAYS }, - { "INSTEAD", "TK_INSTEAD", TRIGGER }, - { "INTERSECT", "TK_INTERSECT", COMPOUND }, - { "INTO", "TK_INTO", ALWAYS }, - { "IS", "TK_IS", ALWAYS }, - { "ISNULL", "TK_ISNULL", ALWAYS }, - { "JOIN", "TK_JOIN", ALWAYS }, - { "KEY", "TK_KEY", ALWAYS }, - { "LEFT", "TK_JOIN_KW", ALWAYS }, - { "LIKE", "TK_LIKE_KW", ALWAYS }, - { "LIMIT", "TK_LIMIT", ALWAYS }, - { "MATCH", "TK_MATCH", ALWAYS }, - { "NATURAL", "TK_JOIN_KW", ALWAYS }, - { "NO", "TK_NO", FKEY }, - { "NOT", "TK_NOT", ALWAYS }, - { "NOTNULL", "TK_NOTNULL", ALWAYS }, - { "NULL", "TK_NULL", ALWAYS }, - { "OF", "TK_OF", ALWAYS }, - { "OFFSET", "TK_OFFSET", ALWAYS }, - { "ON", "TK_ON", ALWAYS }, - { "OR", "TK_OR", ALWAYS }, - { "ORDER", "TK_ORDER", ALWAYS }, - { "OUTER", "TK_JOIN_KW", ALWAYS }, - { "PLAN", "TK_PLAN", EXPLAIN }, - { "PRAGMA", "TK_PRAGMA", PRAGMA }, - { "PRIMARY", "TK_PRIMARY", ALWAYS }, - { "QUERY", "TK_QUERY", EXPLAIN }, - { "RAISE", "TK_RAISE", TRIGGER }, - { "REFERENCES", "TK_REFERENCES", FKEY }, - { "REGEXP", "TK_LIKE_KW", ALWAYS }, - { "REINDEX", "TK_REINDEX", REINDEX }, - { "RELEASE", "TK_RELEASE", ALWAYS }, - { "RENAME", "TK_RENAME", ALTER }, - { "REPLACE", "TK_REPLACE", CONFLICT }, - { "RESTRICT", "TK_RESTRICT", FKEY }, - { "RIGHT", "TK_JOIN_KW", ALWAYS }, - { "ROLLBACK", "TK_ROLLBACK", ALWAYS }, - { "ROW", "TK_ROW", TRIGGER }, - { "SAVEPOINT", "TK_SAVEPOINT", ALWAYS }, - { "SELECT", "TK_SELECT", ALWAYS }, - { "SET", "TK_SET", ALWAYS }, - { "TABLE", "TK_TABLE", ALWAYS }, - { "TEMP", "TK_TEMP", ALWAYS }, - { "TEMPORARY", "TK_TEMP", ALWAYS }, - { "THEN", "TK_THEN", ALWAYS }, - { "TO", "TK_TO", ALWAYS }, - { "TRANSACTION", "TK_TRANSACTION", ALWAYS }, - { "TRIGGER", "TK_TRIGGER", TRIGGER }, - { "UNION", "TK_UNION", COMPOUND }, - { "UNIQUE", "TK_UNIQUE", ALWAYS }, - { "UPDATE", "TK_UPDATE", ALWAYS }, - { "USING", "TK_USING", ALWAYS }, - { "VACUUM", "TK_VACUUM", VACUUM }, - { "VALUES", "TK_VALUES", ALWAYS }, - { "VIEW", "TK_VIEW", VIEW }, - { "VIRTUAL", "TK_VIRTUAL", VTAB }, - { "WHEN", "TK_WHEN", ALWAYS }, - { "WHERE", "TK_WHERE", ALWAYS }, -}; - -/* Number of keywords */ -static int nKeyword = (sizeof(aKeywordTable)/sizeof(aKeywordTable[0])); - -/* An array to map all upper-case characters into their corresponding -** lower-case character. -*/ -const unsigned char sqlite3UpperToLower[] = { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, - 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, - 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, - 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, - 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, - 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, - 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, - 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, - 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, - 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, - 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, - 252,253,254,255 -}; -#define UpperToLower sqlite3UpperToLower - -/* -** Comparision function for two Keyword records -*/ -static int keywordCompare1(const void *a, const void *b){ - const Keyword *pA = (Keyword*)a; - const Keyword *pB = (Keyword*)b; - int n = pA->len - pB->len; - if( n==0 ){ - n = strcmp(pA->zName, pB->zName); - } - assert( n!=0 ); - return n; -} -static int keywordCompare2(const void *a, const void *b){ - const Keyword *pA = (Keyword*)a; - const Keyword *pB = (Keyword*)b; - int n = pB->longestSuffix - pA->longestSuffix; - if( n==0 ){ - n = strcmp(pA->zName, pB->zName); - } - assert( n!=0 ); - return n; -} -static int keywordCompare3(const void *a, const void *b){ - const Keyword *pA = (Keyword*)a; - const Keyword *pB = (Keyword*)b; - int n = pA->offset - pB->offset; - if( n==0 ) n = pB->id - pA->id; - assert( n!=0 ); - return n; -} - -/* -** Return a KeywordTable entry with the given id -*/ -static Keyword *findById(int id){ - int i; - for(i=0; ilen = (int)strlen(p->zName); - assert( p->lenzOrigName) ); - strcpy(p->zOrigName, p->zName); - totalLen += p->len; - p->hash = (UpperToLower[(int)p->zName[0]]*4) ^ - (UpperToLower[(int)p->zName[p->len-1]]*3) ^ p->len; - p->id = i+1; - } - - /* Sort the table from shortest to longest keyword */ - qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare1); - - /* Look for short keywords embedded in longer keywords */ - for(i=nKeyword-2; i>=0; i--){ - Keyword *p = &aKeywordTable[i]; - for(j=nKeyword-1; j>i && p->substrId==0; j--){ - Keyword *pOther = &aKeywordTable[j]; - if( pOther->substrId ) continue; - if( pOther->len<=p->len ) continue; - for(k=0; k<=pOther->len-p->len; k++){ - if( memcmp(p->zName, &pOther->zName[k], p->len)==0 ){ - p->substrId = pOther->id; - p->substrOffset = k; - break; - } - } - } - } - - /* Compute the longestSuffix value for every word */ - for(i=0; isubstrId ) continue; - for(j=0; jsubstrId ) continue; - for(k=p->longestSuffix+1; klen && klen; k++){ - if( memcmp(&p->zName[p->len-k], pOther->zName, k)==0 ){ - p->longestSuffix = k; - } - } - } - } - - /* Sort the table into reverse order by length */ - qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare2); - - /* Fill in the offset for all entries */ - nChar = 0; - for(i=0; ioffset>0 || p->substrId ) continue; - p->offset = nChar; - nChar += p->len; - for(k=p->len-1; k>=1; k--){ - for(j=i+1; joffset>0 || pOther->substrId ) continue; - if( pOther->len<=k ) continue; - if( memcmp(&p->zName[p->len-k], pOther->zName, k)==0 ){ - p = pOther; - p->offset = nChar - k; - nChar = p->offset + p->len; - p->zName += k; - p->len -= k; - p->prefix = k; - j = i; - k = p->len; - } - } - } - } - for(i=0; isubstrId ){ - p->offset = findById(p->substrId)->offset + p->substrOffset; - } - } - - /* Sort the table by offset */ - qsort(aKeywordTable, nKeyword, sizeof(aKeywordTable[0]), keywordCompare3); - - /* Figure out how big to make the hash table in order to minimize the - ** number of collisions */ - bestSize = nKeyword; - bestCount = nKeyword*nKeyword; - for(i=nKeyword/2; i<=2*nKeyword; i++){ - for(j=0; jsubstrId ) continue; - memcpy(&zText[k], p->zName, p->len); - k += p->len; - if( j+p->len>70 ){ - printf("%*s */\n", 74-j, ""); - j = 0; - } - if( j==0 ){ - printf(" /* "); - j = 8; - } - printf("%s", p->zName); - j += p->len; - } - if( j>0 ){ - printf("%*s */\n", 74-j, ""); - } - printf(" static const char zText[%d] = {\n", nChar); - zText[nChar] = 0; - for(i=j=0; i68 ){ - printf("\n"); - j = 0; - } - } - if( j>0 ) printf("\n"); - printf(" };\n"); - - printf(" static const unsigned char aHash[%d] = {\n", bestSize); - for(i=j=0; i12 ){ - printf("\n"); - j = 0; - } - } - printf("%s };\n", j==0 ? "" : "\n"); - - printf(" static const unsigned char aNext[%d] = {\n", nKeyword); - for(i=j=0; i12 ){ - printf("\n"); - j = 0; - } - } - printf("%s };\n", j==0 ? "" : "\n"); - - printf(" static const unsigned char aLen[%d] = {\n", nKeyword); - for(i=j=0; i12 ){ - printf("\n"); - j = 0; - } - } - printf("%s };\n", j==0 ? "" : "\n"); - - printf(" static const unsigned short int aOffset[%d] = {\n", nKeyword); - for(i=j=0; i12 ){ - printf("\n"); - j = 0; - } - } - printf("%s };\n", j==0 ? "" : "\n"); - - printf(" static const unsigned char aCode[%d] = {\n", nKeyword); - for(i=j=0; i=5 ){ - printf("\n"); - j = 0; - } - } - printf("%s };\n", j==0 ? "" : "\n"); - - printf(" int h, i;\n"); - printf(" if( n<2 ) return TK_ID;\n"); - printf(" h = ((charMap(z[0])*4) ^\n" - " (charMap(z[n-1])*3) ^\n" - " n) %% %d;\n", bestSize); - printf(" for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){\n"); - printf(" if( aLen[i]==n &&" - " sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){\n"); - for(i=0; i0} {puts {}} - set col 0 -} - -foreach name [lsort $namelist] { - put_item \"$name\", -} -put_item 0 -finalize -puts " \175;" -puts " enum ${prefix}_enum \173" -foreach name [lsort $namelist] { - regsub -all {@} $name {} name - put_item ${prefix}_[string toupper $name], -} -finalize -puts " \175;" diff --git a/components/external/SQLite-3.8.1/tool/mkpragmatab.tcl b/components/external/SQLite-3.8.1/tool/mkpragmatab.tcl deleted file mode 100644 index 1ba0bd6be9..0000000000 --- a/components/external/SQLite-3.8.1/tool/mkpragmatab.tcl +++ /dev/null @@ -1,393 +0,0 @@ -#!/usr/bin/tclsh -# -# Run this script to generate the pragma name lookup table C code. -# -# To add new pragmas, first add the name and other relevant attributes -# of the pragma to the "pragma_def" object below. Then run this script -# to generate the C-code for the lookup table and copy/paste the output -# of this script into the appropriate spot in the pragma.c source file. -# Then add the extra "case PragTyp_XXXXX:" and subsequent code for the -# new pragma. -# - -set pragma_def { - NAME: full_column_names - TYPE: FLAG - ARG: SQLITE_FullColNames - - NAME: short_column_names - TYPE: FLAG - ARG: SQLITE_ShortColNames - - NAME: count_changes - TYPE: FLAG - ARG: SQLITE_CountRows - - NAME: empty_result_callbacks - TYPE: FLAG - ARG: SQLITE_NullCallback - - NAME: legacy_file_format - TYPE: FLAG - ARG: SQLITE_LegacyFileFmt - - NAME: fullfsync - TYPE: FLAG - ARG: SQLITE_FullFSync - - NAME: checkpoint_fullfsync - TYPE: FLAG - ARG: SQLITE_CkptFullFSync - - NAME: cache_spill - TYPE: FLAG - ARG: SQLITE_CacheSpill - - NAME: reverse_unordered_selects - TYPE: FLAG - ARG: SQLITE_ReverseOrder - - NAME: query_only - TYPE: FLAG - ARG: SQLITE_QueryOnly - - NAME: automatic_index - TYPE: FLAG - ARG: SQLITE_AutoIndex - IF: !defined(SQLITE_OMIT_AUTOMATIC_INDEX) - - NAME: sql_trace - TYPE: FLAG - ARG: SQLITE_SqlTrace - IF: defined(SQLITE_DEBUG) - - NAME: vdbe_listing - TYPE: FLAG - ARG: SQLITE_VdbeListing - IF: defined(SQLITE_DEBUG) - - NAME: vdbe_trace - TYPE: FLAG - ARG: SQLITE_VdbeTrace - IF: defined(SQLITE_DEBUG) - - NAME: vdbe_addoptrace - TYPE: FLAG - ARG: SQLITE_VdbeAddopTrace - IF: defined(SQLITE_DEBUG) - - NAME: vdbe_debug - TYPE: FLAG - ARG: SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace - IF: defined(SQLITE_DEBUG) - - NAME: ignore_check_constraints - TYPE: FLAG - ARG: SQLITE_IgnoreChecks - IF: !defined(SQLITE_OMIT_CHECK) - - NAME: writable_schema - TYPE: FLAG - ARG: SQLITE_WriteSchema|SQLITE_RecoveryMode - - NAME: read_uncommitted - TYPE: FLAG - ARG: SQLITE_ReadUncommitted - - NAME: recursive_triggers - TYPE: FLAG - ARG: SQLITE_RecTriggers - - NAME: foreign_keys - TYPE: FLAG - ARG: SQLITE_ForeignKeys - IF: !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - - NAME: defer_foreign_keys - TYPE: FLAG - ARG: SQLITE_DeferFKs - IF: !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - - NAME: default_cache_size - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) - - NAME: page_size - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: secure_delete - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: page_count - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: max_page_count - TYPE: PAGE_COUNT - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: locking_mode - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: journal_mode - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: journal_size_limit - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: cache_size - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: mmap_size - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: auto_vacuum - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_AUTOVACUUM) - - NAME: incremental_vacuum - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_AUTOVACUUM) - - NAME: temp_store - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: temp_store_directory - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: data_store_directory - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN - - NAME: lock_proxy_file - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE - - NAME: synchronous - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_PAGER_PRAGMAS) - - NAME: table_info - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - - NAME: stats - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - - NAME: index_info - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - - NAME: index_list - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - - NAME: database_list - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - - NAME: collation_list - IF: !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) - - NAME: foreign_key_list - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_FOREIGN_KEY) - - NAME: foreign_key_check - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - - NAME: parser_trace - IF: defined(SQLITE_DEBUG) - - NAME: case_sensitive_like - - NAME: integrity_check - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_INTEGRITY_CHECK) - - NAME: quick_check - TYPE: INTEGRITY_CHECK - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_INTEGRITY_CHECK) - - NAME: encoding - IF: !defined(SQLITE_OMIT_UTF16) - - NAME: schema_version - TYPE: HEADER_VALUE - IF: !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - - NAME: user_version - TYPE: HEADER_VALUE - IF: !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - - NAME: freelist_count - TYPE: HEADER_VALUE - IF: !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - - NAME: application_id - TYPE: HEADER_VALUE - IF: !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS) - - NAME: compile_options - IF: !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS) - - NAME: wal_checkpoint - FLAG: NeedSchema - IF: !defined(SQLITE_OMIT_WAL) - - NAME: wal_autocheckpoint - IF: !defined(SQLITE_OMIT_WAL) - - NAME: shrink_memory - - NAME: busy_timeout - - NAME: lock_status - IF: defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - - NAME: key - IF: defined(SQLITE_HAS_CODEC) - - NAME: rekey - IF: defined(SQLITE_HAS_CODEC) - - NAME: hexkey - IF: defined(SQLITE_HAS_CODEC) - - NAME: hexrekey - TYPE: HEXKEY - IF: defined(SQLITE_HAS_CODEC) - - NAME: activate_extensions - IF: defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) - - NAME: soft_heap_limit -} -set name {} -set type {} -set if {} -set flags {} -set arg 0 -proc record_one {} { - global name type if arg allbyname typebyif flags - if {$name==""} return - set allbyname($name) [list $type $arg $if $flags] - set name {} - set type {} - set if {} - set flags {} - set arg 0 -} -foreach line [split $pragma_def \n] { - set line [string trim $line] - if {$line==""} continue - foreach {id val} [split $line :] break - set val [string trim $val] - if {$id=="NAME"} { - record_one - set name $val - set type [string toupper $val] - } elseif {$id=="TYPE"} { - set type $val - } elseif {$id=="ARG"} { - set arg $val - } elseif {$id=="IF"} { - set if $val - } elseif {$id=="FLAG"} { - foreach term [split $val] { - lappend flags $term - set allflags($term) 1 - } - } else { - error "bad pragma_def line: $line" - } -} -record_one -set allnames [lsort [array names allbyname]] - -# Generate #defines for all pragma type names. Group the pragmas that are -# omit in default builds (defined(SQLITE_DEBUG) and defined(SQLITE_HAS_CODEC)) -# at the end. -# -set pnum 0 -foreach name $allnames { - set type [lindex $allbyname($name) 0] - if {[info exists seentype($type)]} continue - set if [lindex $allbyname($name) 2] - if {[regexp SQLITE_DEBUG $if] || [regexp SQLITE_HAS_CODEC $if]} continue - set seentype($type) 1 - puts [format {#define %-35s %4d} PragTyp_$type $pnum] - incr pnum -} -foreach name $allnames { - set type [lindex $allbyname($name) 0] - if {[info exists seentype($type)]} continue - set if [lindex $allbyname($name) 2] - if {[regexp SQLITE_DEBUG $if]} continue - set seentype($type) 1 - puts [format {#define %-35s %4d} PragTyp_$type $pnum] - incr pnum -} -foreach name $allnames { - set type [lindex $allbyname($name) 0] - if {[info exists seentype($type)]} continue - set seentype($type) 1 - puts [format {#define %-35s %4d} PragTyp_$type $pnum] - incr pnum -} - -# Generate #defines for flags -# -set fv 1 -foreach f [lsort [array names allflags]] { - puts [format {#define PragFlag_%-20s 0x%02x} $f $fv] - set fv [expr {$fv*2}] -} - -# Generate the lookup table -# -puts "static const struct sPragmaNames \173" -puts " const char *const zName; /* Name of pragma */" -puts " u8 ePragTyp; /* PragTyp_XXX value */" -puts " u8 mPragFlag; /* Zero or more PragFlag_XXX values */" -puts " u32 iArg; /* Extra argument */" -puts "\175 aPragmaNames\[\] = \173" - -set current_if {} -set spacer [format { %26s } {}] -foreach name $allnames { - foreach {type arg if flag} $allbyname($name) break - if {$if!=$current_if} { - if {$current_if!=""} {puts "#endif"} - set current_if $if - if {$current_if!=""} {puts "#if $current_if"} - } - set typex [format PragTyp_%-23s $type,] - if {$flag==""} { - set flagx "0" - } else { - set flagx PragFlag_[join $flag {|PragFlag_}] - } - puts " \173 /* zName: */ \"$name\"," - puts " /* ePragTyp: */ PragTyp_$type," - puts " /* ePragFlag: */ $flagx," - puts " /* iArg: */ $arg \175," -} -if {$current_if!=""} {puts "#endif"} -puts "\175;" - -# count the number of pragmas, for information purposes -# -set allcnt 0 -set dfltcnt 0 -foreach name $allnames { - incr allcnt - set if [lindex $allbyname($name) 2] - if {[regexp {^defined} $if] || [regexp {[^!]defined} $if]} continue - incr dfltcnt -} -puts "/* Number of pragmas: $dfltcnt on by default, $allcnt total. */" diff --git a/components/external/SQLite-3.8.1/tool/mkspeedsql.tcl b/components/external/SQLite-3.8.1/tool/mkspeedsql.tcl deleted file mode 100644 index 04bafc04c1..0000000000 --- a/components/external/SQLite-3.8.1/tool/mkspeedsql.tcl +++ /dev/null @@ -1,237 +0,0 @@ -# 2008 October 9 -# -# The author disclaims copyright to this source code. In place of -# a legal notice, here is a blessing: -# -# May you do good and not evil. -# May you find forgiveness for yourself and forgive others. -# May you share freely, never taking more than you give. -# -#************************************************************************* -# This file generates SQL text used for performance testing. -# -# $Id: mkspeedsql.tcl,v 1.1 2008/10/09 17:57:34 drh Exp $ -# - -# Set a uniform random seed -expr srand(0) - -# The number_name procedure below converts its argment (an integer) -# into a string which is the English-language name for that number. -# -# Example: -# -# puts [number_name 123] -> "one hundred twenty three" -# -set ones {zero one two three four five six seven eight nine - ten eleven twelve thirteen fourteen fifteen sixteen seventeen - eighteen nineteen} -set tens {{} ten twenty thirty forty fifty sixty seventy eighty ninety} -proc number_name {n} { - if {$n>=1000} { - set txt "[number_name [expr {$n/1000}]] thousand" - set n [expr {$n%1000}] - } else { - set txt {} - } - if {$n>=100} { - append txt " [lindex $::ones [expr {$n/100}]] hundred" - set n [expr {$n%100}] - } - if {$n>=20} { - append txt " [lindex $::tens [expr {$n/10}]]" - set n [expr {$n%10}] - } - if {$n>0} { - append txt " [lindex $::ones $n]" - } - set txt [string trim $txt] - if {$txt==""} {set txt zero} - return $txt -} - -# Create a database schema. -# -puts { - PRAGMA page_size=1024; - PRAGMA cache_size=8192; - PRAGMA locking_mode=EXCLUSIVE; - CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); - CREATE TABLE t2(a INTEGER, b INTEGER, c TEXT); - CREATE INDEX i2a ON t2(a); - CREATE INDEX i2b ON t2(b); - SELECT name FROM sqlite_master ORDER BY 1; -} - - -# 50000 INSERTs on an unindexed table -# -set t1c_list {} -puts {BEGIN;} -for {set i 1} {$i<=50000} {incr i} { - set r [expr {int(rand()*500000)}] - set x [number_name $r] - lappend t1c_list $x - puts "INSERT INTO t1 VALUES($i,$r,'$x');" -} -puts {COMMIT;} - -# 50000 INSERTs on an indexed table -# -puts {BEGIN;} -for {set i 1} {$i<=50000} {incr i} { - set r [expr {int(rand()*500000)}] - puts "INSERT INTO t2 VALUES($i,$r,'[number_name $r]');" -} -puts {COMMIT;} - - -# 50 SELECTs on an integer comparison. There is no index so -# a full table scan is required. -# -for {set i 0} {$i<50} {incr i} { - set lwr [expr {$i*100}] - set upr [expr {($i+10)*100}] - puts "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;" -} - -# 50 SELECTs on an LIKE comparison. There is no index so a full -# table scan is required. -# -for {set i 0} {$i<50} {incr i} { - puts "SELECT count(*), avg(b) FROM t1 WHERE c LIKE '%[number_name $i]%';" -} - -# Create indices -# -puts {BEGIN;} -puts { - CREATE INDEX i1a ON t1(a); - CREATE INDEX i1b ON t1(b); - CREATE INDEX i1c ON t1(c); -} -puts {COMMIT;} - -# 5000 SELECTs on an integer comparison where the integer is -# indexed. -# -set sql {} -for {set i 0} {$i<5000} {incr i} { - set lwr [expr {$i*100}] - set upr [expr {($i+10)*100}] - puts "SELECT count(*), avg(b) FROM t1 WHERE b>=$lwr AND b<$upr;" -} - -# 100000 random SELECTs against rowid. -# -for {set i 1} {$i<=100000} {incr i} { - set id [expr {int(rand()*50000)+1}] - puts "SELECT c FROM t1 WHERE rowid=$id;" -} - -# 100000 random SELECTs against a unique indexed column. -# -for {set i 1} {$i<=100000} {incr i} { - set id [expr {int(rand()*50000)+1}] - puts "SELECT c FROM t1 WHERE a=$id;" -} - -# 50000 random SELECTs against an indexed column text column -# -set nt1c [llength $t1c_list] -for {set i 0} {$i<50000} {incr i} { - set r [expr {int(rand()*$nt1c)}] - set c [lindex $t1c_list $i] - puts "SELECT c FROM t1 WHERE c='$c';" -} - - -# Vacuum -puts {VACUUM;} - -# 5000 updates of ranges where the field being compared is indexed. -# -puts {BEGIN;} -for {set i 0} {$i<5000} {incr i} { - set lwr [expr {$i*2}] - set upr [expr {($i+1)*2}] - puts "UPDATE t1 SET b=b*2 WHERE a>=$lwr AND a<$upr;" -} -puts {COMMIT;} - -# 50000 single-row updates. An index is used to find the row quickly. -# -puts {BEGIN;} -for {set i 0} {$i<50000} {incr i} { - set r [expr {int(rand()*500000)}] - puts "UPDATE t1 SET b=$r WHERE a=$i;" -} -puts {COMMIT;} - -# 1 big text update that touches every row in the table. -# -puts { - UPDATE t1 SET c=a; -} - -# Many individual text updates. Each row in the table is -# touched through an index. -# -puts {BEGIN;} -for {set i 1} {$i<=50000} {incr i} { - set r [expr {int(rand()*500000)}] - puts "UPDATE t1 SET c='[number_name $r]' WHERE a=$i;" -} -puts {COMMIT;} - -# Delete all content in a table. -# -puts {DELETE FROM t1;} - -# Copy one table into another -# -puts {INSERT INTO t1 SELECT * FROM t2;} - -# Delete all content in a table, one row at a time. -# -puts {DELETE FROM t1 WHERE 1;} - -# Refill the table yet again -# -puts {INSERT INTO t1 SELECT * FROM t2;} - -# Drop the table and recreate it without its indices. -# -puts {BEGIN;} -puts { - DROP TABLE t1; - CREATE TABLE t1(a INTEGER, b INTEGER, c TEXT); -} -puts {COMMIT;} - -# Refill the table yet again. This copy should be faster because -# there are no indices to deal with. -# -puts {INSERT INTO t1 SELECT * FROM t2;} - -# Select 20000 rows from the table at random. -# -puts { - SELECT rowid FROM t1 ORDER BY random() LIMIT 20000; -} - -# Delete 20000 random rows from the table. -# -puts { - DELETE FROM t1 WHERE rowid IN - (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000); -} -puts {SELECT count(*) FROM t1;} - -# Delete 20000 more rows at random from the table. -# -puts { - DELETE FROM t1 WHERE rowid IN - (SELECT rowid FROM t1 ORDER BY random() LIMIT 20000); -} -puts {SELECT count(*) FROM t1;} diff --git a/components/external/SQLite-3.8.1/tool/mksqlite3c-noext.tcl b/components/external/SQLite-3.8.1/tool/mksqlite3c-noext.tcl deleted file mode 100644 index 017ad6292f..0000000000 --- a/components/external/SQLite-3.8.1/tool/mksqlite3c-noext.tcl +++ /dev/null @@ -1,305 +0,0 @@ -#!/usr/bin/tclsh -# -# To build a single huge source file holding all of SQLite (or at -# least the core components - the test harness, shell, and TCL -# interface are omitted.) first do -# -# make target_source -# -# The make target above moves all of the source code files into -# a subdirectory named "tsrc". (This script expects to find the files -# there and will not work if they are not found.) There are a few -# generated C code files that are also added to the tsrc directory. -# For example, the "parse.c" and "parse.h" files to implement the -# the parser are derived from "parse.y" using lemon. And the -# "keywordhash.h" files is generated by a program named "mkkeywordhash". -# -# After the "tsrc" directory has been created and populated, run -# this script: -# -# tclsh mksqlite3c.tcl -# -# The amalgamated SQLite code will be written into sqlite3.c -# - -# Begin by reading the "sqlite3.h" header file. Extract the version number -# from in this file. The versioon number is needed to generate the header -# comment of the amalgamation. -# -if {[lsearch $argv --nostatic]>=0} { - set addstatic 0 -} else { - set addstatic 1 -} -if {[lsearch $argv --linemacros]>=0} { - set linemacros 1 -} else { - set linemacros 0 -} -set in [open tsrc/sqlite3.h] -set cnt 0 -set VERSION ????? -while {![eof $in]} { - set line [gets $in] - if {$line=="" && [eof $in]} break - incr cnt - regexp {#define\s+SQLITE_VERSION\s+"(.*)"} $line all VERSION -} -close $in - -# Open the output file and write a header comment at the beginning -# of the file. -# -set out [open sqlite3.c w] -# Force the output to use unix line endings, even on Windows. -fconfigure $out -translation lf -set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1] -puts $out [subst \ -{/****************************************************************************** -** This file is an amalgamation of many separate C source files from SQLite -** version $VERSION. By combining all the individual C code files into this -** single large file, the entire code can be compiled as a single translation -** unit. This allows many compilers to do optimizations that would not be -** possible if the files were compiled separately. Performance improvements -** of 5% or more are commonly seen when SQLite is compiled as a single -** translation unit. -** -** This file is all you need to compile SQLite. To use SQLite in other -** programs, you need this file and the "sqlite3.h" header file that defines -** the programming interface to the SQLite library. (If you do not have -** the "sqlite3.h" header file at hand, you will find a copy embedded within -** the text of this file. Search for "Begin file sqlite3.h" to find the start -** of the embedded sqlite3.h header file.) Additional code files may be needed -** if you want a wrapper to interface SQLite with your choice of programming -** language. The code for the "sqlite3" command-line shell is also in a -** separate file. This file contains only code for the core SQLite library. -*/ -#define SQLITE_CORE 1 -#define SQLITE_AMALGAMATION 1}] -if {$addstatic} { - puts $out \ -{#ifndef SQLITE_PRIVATE -# define SQLITE_PRIVATE static -#endif -#ifndef SQLITE_API -# define SQLITE_API -#endif} -} - -# These are the header files used by SQLite. The first time any of these -# files are seen in a #include statement in the C code, include the complete -# text of the file in-line. The file only needs to be included once. -# -foreach hdr { - btree.h - btreeInt.h - hash.h - hwtime.h - keywordhash.h - mutex.h - opcodes.h - os_common.h - os.h - pager.h - parse.h - pcache.h - sqlite3ext.h - sqlite3.h - sqliteicu.h - sqliteInt.h - sqliteLimit.h - vdbe.h - vdbeInt.h - wal.h -} { - set available_hdr($hdr) 1 -} -set available_hdr(sqliteInt.h) 0 - -# 78 stars used for comment formatting. -set s78 \ -{*****************************************************************************} - -# Insert a comment into the code -# -proc section_comment {text} { - global out s78 - set n [string length $text] - set nstar [expr {60 - $n}] - set stars [string range $s78 0 $nstar] - puts $out "/************** $text $stars/" -} - -# Read the source file named $filename and write it into the -# sqlite3.c output file. If any #include statements are seen, -# process them approprately. -# -proc copy_file {filename} { - global seen_hdr available_hdr out addstatic linemacros - set ln 0 - set tail [file tail $filename] - section_comment "Begin file $tail" - if {$linemacros} {puts $out "#line 1 \"$filename\""} - set in [open $filename r] - set varpattern {^[a-zA-Z][a-zA-Z_0-9 *]+(sqlite3[_a-zA-Z0-9]+)(\[|;| =)} - set declpattern {[a-zA-Z][a-zA-Z_0-9 ]+ \**(sqlite3[_a-zA-Z0-9]+)\(} - if {[file extension $filename]==".h"} { - set declpattern " *$declpattern" - } - set declpattern ^$declpattern - while {![eof $in]} { - set line [gets $in] - incr ln - if {[regexp {^\s*#\s*include\s+["<]([^">]+)[">]} $line all hdr]} { - if {[info exists available_hdr($hdr)]} { - if {$available_hdr($hdr)} { - if {$hdr!="os_common.h" && $hdr!="hwtime.h"} { - set available_hdr($hdr) 0 - } - section_comment "Include $hdr in the middle of $tail" - copy_file tsrc/$hdr - section_comment "Continuing where we left off in $tail" - if {$linemacros} {puts $out "#line [expr {$ln+1}] \"$filename\""} - } - } elseif {![info exists seen_hdr($hdr)]} { - set seen_hdr($hdr) 1 - puts $out $line - } else { - puts $out "/* $line */" - } - } elseif {[regexp {^#ifdef __cplusplus} $line]} { - puts $out "#if 0" - } elseif {!$linemacros && [regexp {^#line} $line]} { - # Skip #line directives. - } elseif {$addstatic && ![regexp {^(static|typedef)} $line]} { - regsub {^SQLITE_API } $line {} line - if {[regexp $declpattern $line all funcname]} { - # Add the SQLITE_PRIVATE or SQLITE_API keyword before functions. - # so that linkage can be modified at compile-time. - if {[regexp {^sqlite3_} $funcname]} { - puts $out "SQLITE_API $line" - } else { - puts $out "SQLITE_PRIVATE $line" - } - } elseif {[regexp $varpattern $line all varname]} { - # Add the SQLITE_PRIVATE before variable declarations or - # definitions for internal use - if {![regexp {^sqlite3_} $varname]} { - regsub {^extern } $line {} line - puts $out "SQLITE_PRIVATE $line" - } else { - if {[regexp {const char sqlite3_version\[\];} $line]} { - set line {const char sqlite3_version[] = SQLITE_VERSION;} - } - regsub {^SQLITE_EXTERN } $line {} line - puts $out "SQLITE_API $line" - } - } elseif {[regexp {^(SQLITE_EXTERN )?void \(\*sqlite3IoTrace\)} $line]} { - regsub {^SQLITE_EXTERN } $line {} line - puts $out "SQLITE_PRIVATE $line" - } elseif {[regexp {^void \(\*sqlite3Os} $line]} { - puts $out "SQLITE_PRIVATE $line" - } else { - puts $out $line - } - } else { - puts $out $line - } - } - close $in - section_comment "End of $tail" -} - - -# Process the source files. Process files containing commonly -# used subroutines first in order to help the compiler find -# inlining opportunities. -# -foreach file { - sqliteInt.h - - global.c - ctime.c - status.c - date.c - os.c - - fault.c - mem0.c - mem1.c - mem2.c - mem3.c - mem5.c - mutex.c - mutex_noop.c - mutex_unix.c - mutex_w32.c - malloc.c - printf.c - random.c - utf.c - util.c - hash.c - opcodes.c - - os_unix.c - os_win.c - - bitvec.c - pcache.c - pcache1.c - rowset.c - pager.c - wal.c - - btmutex.c - btree.c - backup.c - - vdbemem.c - vdbeaux.c - vdbeapi.c - vdbetrace.c - vdbe.c - vdbeblob.c - vdbesort.c - journal.c - memjournal.c - - walker.c - resolve.c - expr.c - alter.c - analyze.c - attach.c - auth.c - build.c - callback.c - delete.c - func.c - fkey.c - insert.c - legacy.c - loadext.c - pragma.c - prepare.c - select.c - table.c - trigger.c - update.c - vacuum.c - vtab.c - where.c - - parse.c - - tokenize.c - complete.c - - main.c - notify.c -} { - copy_file tsrc/$file -} - -close $out diff --git a/components/external/SQLite-3.8.1/tool/mksqlite3c.tcl b/components/external/SQLite-3.8.1/tool/mksqlite3c.tcl deleted file mode 100644 index 89d73a6641..0000000000 --- a/components/external/SQLite-3.8.1/tool/mksqlite3c.tcl +++ /dev/null @@ -1,334 +0,0 @@ -#!/usr/bin/tclsh -# -# To build a single huge source file holding all of SQLite (or at -# least the core components - the test harness, shell, and TCL -# interface are omitted.) first do -# -# make target_source -# -# The make target above moves all of the source code files into -# a subdirectory named "tsrc". (This script expects to find the files -# there and will not work if they are not found.) There are a few -# generated C code files that are also added to the tsrc directory. -# For example, the "parse.c" and "parse.h" files to implement the -# the parser are derived from "parse.y" using lemon. And the -# "keywordhash.h" files is generated by a program named "mkkeywordhash". -# -# After the "tsrc" directory has been created and populated, run -# this script: -# -# tclsh mksqlite3c.tcl -# -# The amalgamated SQLite code will be written into sqlite3.c -# - -# Begin by reading the "sqlite3.h" header file. Extract the version number -# from in this file. The version number is needed to generate the header -# comment of the amalgamation. -# -if {[lsearch $argv --nostatic]>=0} { - set addstatic 0 -} else { - set addstatic 1 -} -if {[lsearch $argv --linemacros]>=0} { - set linemacros 1 -} else { - set linemacros 0 -} -set in [open tsrc/sqlite3.h] -set cnt 0 -set VERSION ????? -while {![eof $in]} { - set line [gets $in] - if {$line=="" && [eof $in]} break - incr cnt - regexp {#define\s+SQLITE_VERSION\s+"(.*)"} $line all VERSION -} -close $in - -# Open the output file and write a header comment at the beginning -# of the file. -# -set out [open sqlite3.c w] -# Force the output to use unix line endings, even on Windows. -fconfigure $out -translation lf -set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1] -puts $out [subst \ -{/****************************************************************************** -** This file is an amalgamation of many separate C source files from SQLite -** version $VERSION. By combining all the individual C code files into this -** single large file, the entire code can be compiled as a single translation -** unit. This allows many compilers to do optimizations that would not be -** possible if the files were compiled separately. Performance improvements -** of 5% or more are commonly seen when SQLite is compiled as a single -** translation unit. -** -** This file is all you need to compile SQLite. To use SQLite in other -** programs, you need this file and the "sqlite3.h" header file that defines -** the programming interface to the SQLite library. (If you do not have -** the "sqlite3.h" header file at hand, you will find a copy embedded within -** the text of this file. Search for "Begin file sqlite3.h" to find the start -** of the embedded sqlite3.h header file.) Additional code files may be needed -** if you want a wrapper to interface SQLite with your choice of programming -** language. The code for the "sqlite3" command-line shell is also in a -** separate file. This file contains only code for the core SQLite library. -*/ -#define SQLITE_CORE 1 -#define SQLITE_AMALGAMATION 1}] -if {$addstatic} { - puts $out \ -{#ifndef SQLITE_PRIVATE -# define SQLITE_PRIVATE static -#endif -#ifndef SQLITE_API -# define SQLITE_API -#endif} -} - -# These are the header files used by SQLite. The first time any of these -# files are seen in a #include statement in the C code, include the complete -# text of the file in-line. The file only needs to be included once. -# -foreach hdr { - btree.h - btreeInt.h - fts3.h - fts3Int.h - fts3_hash.h - fts3_tokenizer.h - hash.h - hwtime.h - keywordhash.h - mutex.h - opcodes.h - os_common.h - os.h - pager.h - parse.h - pcache.h - rtree.h - sqlite3ext.h - sqlite3.h - sqliteicu.h - sqliteInt.h - sqliteLimit.h - vdbe.h - vdbeInt.h - wal.h -} { - set available_hdr($hdr) 1 -} -set available_hdr(sqliteInt.h) 0 -set available_hdr(sqlite3.h) 0 - -# 78 stars used for comment formatting. -set s78 \ -{*****************************************************************************} - -# Insert a comment into the code -# -proc section_comment {text} { - global out s78 - set n [string length $text] - set nstar [expr {60 - $n}] - set stars [string range $s78 0 $nstar] - puts $out "/************** $text $stars/" -} - -# Read the source file named $filename and write it into the -# sqlite3.c output file. If any #include statements are seen, -# process them appropriately. -# -proc copy_file {filename} { - global seen_hdr available_hdr out addstatic linemacros - set ln 0 - set tail [file tail $filename] - section_comment "Begin file $tail" - if {$linemacros} {puts $out "#line 1 \"$filename\""} - set in [open $filename r] - set varpattern {^[a-zA-Z][a-zA-Z_0-9 *]+(sqlite3[_a-zA-Z0-9]+)(\[|;| =)} - set declpattern {[a-zA-Z][a-zA-Z_0-9 ]+ \**(sqlite3[_a-zA-Z0-9]+)\(} - if {[file extension $filename]==".h"} { - set declpattern " *$declpattern" - } - set declpattern ^$declpattern - while {![eof $in]} { - set line [gets $in] - incr ln - if {[regexp {^\s*#\s*include\s+["<]([^">]+)[">]} $line all hdr]} { - if {[info exists available_hdr($hdr)]} { - if {$available_hdr($hdr)} { - if {$hdr!="os_common.h" && $hdr!="hwtime.h"} { - set available_hdr($hdr) 0 - } - section_comment "Include $hdr in the middle of $tail" - copy_file tsrc/$hdr - section_comment "Continuing where we left off in $tail" - if {$linemacros} {puts $out "#line [expr {$ln+1}] \"$filename\""} - } - } elseif {![info exists seen_hdr($hdr)]} { - set seen_hdr($hdr) 1 - puts $out $line - } elseif {[regexp {/\*\s+amalgamator:\s+keep\s+\*/} $line]} { - # This include file must be kept because there was a "keep" - # directive inside of a line comment. - puts $out $line - } else { - # Comment out the entire line, replacing any nested comment - # begin/end markers with the harmless substring "**". - puts $out "/* [string map [list /* ** */ **] $line] */" - } - } elseif {[regexp {^#ifdef __cplusplus} $line]} { - puts $out "#if 0" - } elseif {!$linemacros && [regexp {^#line} $line]} { - # Skip #line directives. - } elseif {$addstatic && ![regexp {^(static|typedef)} $line]} { - regsub {^SQLITE_API } $line {} line - if {[regexp $declpattern $line all funcname]} { - # Add the SQLITE_PRIVATE or SQLITE_API keyword before functions. - # so that linkage can be modified at compile-time. - if {[regexp {^sqlite3_} $funcname]} { - puts $out "SQLITE_API $line" - } else { - puts $out "SQLITE_PRIVATE $line" - } - } elseif {[regexp $varpattern $line all varname]} { - # Add the SQLITE_PRIVATE before variable declarations or - # definitions for internal use - if {![regexp {^sqlite3_} $varname]} { - regsub {^extern } $line {} line - puts $out "SQLITE_PRIVATE $line" - } else { - if {[regexp {const char sqlite3_version\[\];} $line]} { - set line {const char sqlite3_version[] = SQLITE_VERSION;} - } - regsub {^SQLITE_EXTERN } $line {} line - puts $out "SQLITE_API $line" - } - } elseif {[regexp {^(SQLITE_EXTERN )?void \(\*sqlite3IoTrace\)} $line]} { - regsub {^SQLITE_EXTERN } $line {} line - puts $out "SQLITE_PRIVATE $line" - } elseif {[regexp {^void \(\*sqlite3Os} $line]} { - puts $out "SQLITE_PRIVATE $line" - } else { - puts $out $line - } - } else { - puts $out $line - } - } - close $in - section_comment "End of $tail" -} - - -# Process the source files. Process files containing commonly -# used subroutines first in order to help the compiler find -# inlining opportunities. -# -foreach file { - sqlite_config_rtthread.h - sqlite3.h - sqliteInt.h - - global.c - ctime.c - status.c - date.c - os.c - - fault.c - mem0.c - mem1.c - mem2.c - mem3.c - mem5.c - mutex.c - mutex_noop.c - mutex_rtthread.c - malloc.c - printf.c - random.c - utf.c - util.c - hash.c - opcodes.c - - os_rtthread.c - - bitvec.c - pcache.c - pcache1.c - rowset.c - pager.c - wal.c - - btmutex.c - btree.c - backup.c - - vdbemem.c - vdbeaux.c - vdbeapi.c - vdbetrace.c - vdbe.c - vdbeblob.c - vdbesort.c - journal.c - memjournal.c - - walker.c - resolve.c - expr.c - alter.c - analyze.c - attach.c - auth.c - build.c - callback.c - delete.c - func.c - fkey.c - insert.c - legacy.c - loadext.c - pragma.c - prepare.c - select.c - table.c - trigger.c - update.c - vacuum.c - vtab.c - where.c - - parse.c - - tokenize.c - complete.c - - main.c - notify.c - - fts3.c - fts3_aux.c - fts3_expr.c - fts3_hash.c - fts3_porter.c - fts3_tokenizer.c - fts3_tokenizer1.c - fts3_tokenize_vtab.c - fts3_write.c - fts3_snippet.c - fts3_unicode.c - fts3_unicode2.c - - rtree.c - icu.c - fts3_icu.c -} { - copy_file tsrc/$file -} - -close $out diff --git a/components/external/SQLite-3.8.1/tool/mksqlite3h.tcl b/components/external/SQLite-3.8.1/tool/mksqlite3h.tcl deleted file mode 100644 index a89b9f9beb..0000000000 --- a/components/external/SQLite-3.8.1/tool/mksqlite3h.tcl +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/tclsh -# -# This script constructs the "sqlite3.h" header file from the following -# sources: -# -# 1) The src/sqlite.h.in source file. This is the template for sqlite3.h. -# 2) The VERSION file containing the current SQLite version number. -# 3) The manifest file from the fossil SCM. This gives use the date. -# 4) The manifest.uuid file from the fossil SCM. This gives the SHA1 hash. -# -# Run this script by specifying the root directory of the source tree -# on the command-line. -# -# This script performs processing on src/sqlite.h.in. It: -# -# 1) Adds SQLITE_EXTERN in front of the declaration of global variables, -# 2) Adds SQLITE_API in front of the declaration of API functions, -# 3) Replaces the string --VERS-- with the current library version, -# formatted as a string (e.g. "3.6.17"), and -# 4) Replaces the string --VERSION-NUMBER-- with current library version, -# formatted as an integer (e.g. "3006017"). -# 5) Replaces the string --SOURCE-ID-- with the date and time and sha1 -# hash of the fossil-scm manifest for the source tree. -# -# This script outputs to stdout. -# -# Example usage: -# -# tclsh mksqlite3h.tcl ../sqlite >sqlite3.h -# - - -# Get the source tree root directory from the command-line -# -set TOP [lindex $argv 0] - -# Get the SQLite version number (ex: 3.6.18) from the $TOP/VERSION file. -# -set in [open $TOP/VERSION] -set zVersion [string trim [read $in]] -close $in -set nVersion [eval format "%d%03d%03d" [split $zVersion .]] - -# Get the fossil-scm version number from $TOP/manifest.uuid. -# -set in [open $TOP/manifest.uuid] -set zUuid [string trim [read $in]] -close $in - -# Get the fossil-scm check-in date from the "D" card of $TOP/manifest. -# -set in [open $TOP/manifest] -set zDate {} -while {![eof $in]} { - set line [gets $in] - if {[regexp {^D (2[-0-9T:]+)} $line all date]} { - set zDate [string map {T { }} $date] - break - } -} -close $in - -# Set up patterns for recognizing API declarations. -# -set varpattern {^[a-zA-Z][a-zA-Z_0-9 *]+sqlite3_[_a-zA-Z0-9]+(\[|;| =)} -set declpattern {^ *[a-zA-Z][a-zA-Z_0-9 ]+ \**sqlite3_[_a-zA-Z0-9]+\(} - -# Force the output to use unix line endings, even on Windows. -fconfigure stdout -translation lf - -set filelist [subst { - $TOP/src/sqlite.h.in - $TOP/ext/rtree/sqlite3rtree.h -}] - -# Process the source files. -# -foreach file $filelist { - set in [open $file] - while {![eof $in]} { - - set line [gets $in] - - # File sqlite3rtree.h contains a line "#include ". Omit this - # line when copying sqlite3rtree.h into sqlite3.h. - # - if {[string match {*#include**} $line]} continue - - regsub -- --VERS-- $line $zVersion line - regsub -- --VERSION-NUMBER-- $line $nVersion line - regsub -- --SOURCE-ID-- $line "$zDate $zUuid" line - - if {[regexp {define SQLITE_EXTERN extern} $line]} { - puts $line - puts [gets $in] - puts "" - puts "#ifndef SQLITE_API" - puts "# define SQLITE_API" - puts "#endif" - set line "" - } - - if {([regexp $varpattern $line] && ![regexp {^ *typedef} $line]) - || ([regexp $declpattern $line]) - } { - set line "SQLITE_API $line" - } - puts $line - } - close $in -} diff --git a/components/external/SQLite-3.8.1/tool/mksqlite3internalh.tcl b/components/external/SQLite-3.8.1/tool/mksqlite3internalh.tcl deleted file mode 100644 index 406ef5c457..0000000000 --- a/components/external/SQLite-3.8.1/tool/mksqlite3internalh.tcl +++ /dev/null @@ -1,145 +0,0 @@ -#!/usr/bin/tclsh -# -# To build a single huge source file holding all of SQLite (or at -# least the core components - the test harness, shell, and TCL -# interface are omitted.) first do -# -# make target_source -# -# The make target above moves all of the source code files into -# a subdirectory named "tsrc". (This script expects to find the files -# there and will not work if they are not found.) There are a few -# generated C code files that are also added to the tsrc directory. -# For example, the "parse.c" and "parse.h" files to implement the -# the parser are derived from "parse.y" using lemon. And the -# "keywordhash.h" files is generated by a program named "mkkeywordhash". -# -# After the "tsrc" directory has been created and populated, run -# this script: -# -# tclsh mksqlite3c.tcl -# -# The amalgamated SQLite code will be written into sqlite3.c -# - -# Begin by reading the "sqlite3.h" header file. Count the number of lines -# in this file and extract the version number. That information will be -# needed in order to generate the header of the amalgamation. -# -set in [open tsrc/sqlite3.h] -set cnt 0 -set VERSION ????? -while {![eof $in]} { - set line [gets $in] - if {$line=="" && [eof $in]} break - incr cnt - regexp {#define\s+SQLITE_VERSION\s+"(.*)"} $line all VERSION -} -close $in - -# Open the output file and write a header comment at the beginning -# of the file. -# -set out [open sqlite3internal.h w] -set today [clock format [clock seconds] -format "%Y-%m-%d %H:%M:%S UTC" -gmt 1] -puts $out [subst \ -{/****************************************************************************** -** This file is an amalgamation of many private header files from SQLite -** version $VERSION. -*/}] - -# These are the header files used by SQLite. The first time any of these -# files are seen in a #include statement in the C code, include the complete -# text of the file in-line. The file only needs to be included once. -# -foreach hdr { - btree.h - btreeInt.h - hash.h - hwtime.h - keywordhash.h - opcodes.h - os_common.h - os.h - pager.h - parse.h - sqlite3ext.h - sqlite3.h - sqliteInt.h - sqliteLimit.h - vdbe.h - vdbeInt.h -} { - set available_hdr($hdr) 1 -} - -# 78 stars used for comment formatting. -set s78 \ -{*****************************************************************************} - -# Insert a comment into the code -# -proc section_comment {text} { - global out s78 - set n [string length $text] - set nstar [expr {60 - $n}] - set stars [string range $s78 0 $nstar] - puts $out "/************** $text $stars/" -} - -# Read the source file named $filename and write it into the -# sqlite3.c output file. If any #include statements are seen, -# process them approprately. -# -proc copy_file {filename} { - global seen_hdr available_hdr out - set tail [file tail $filename] - section_comment "Begin file $tail" - set in [open $filename r] - while {![eof $in]} { - set line [gets $in] - if {[regexp {^#\s*include\s+["<]([^">]+)[">]} $line all hdr]} { - if {[info exists available_hdr($hdr)]} { - if {$available_hdr($hdr)} { - section_comment "Include $hdr in the middle of $tail" - copy_file tsrc/$hdr - section_comment "Continuing where we left off in $tail" - } - } elseif {![info exists seen_hdr($hdr)]} { - set seen_hdr($hdr) 1 - puts $out $line - } - } elseif {[regexp {^#ifdef __cplusplus} $line]} { - puts $out "#if 0" - } elseif {[regexp {^#line} $line]} { - # Skip #line directives. - } else { - puts $out $line - } - } - close $in - section_comment "End of $tail" -} - - -# Process the source files. Process files containing commonly -# used subroutines first in order to help the compiler find -# inlining opportunities. -# -foreach file { - sqliteInt.h - sqlite3.h - btree.h - hash.h - os.h - pager.h - parse.h - sqlite3ext.h - vdbe.h -} { - if {$available_hdr($file)} { - copy_file tsrc/$file - } -} - -close $out diff --git a/components/external/SQLite-3.8.1/tool/mkvsix.tcl b/components/external/SQLite-3.8.1/tool/mkvsix.tcl deleted file mode 100644 index 65fa731245..0000000000 --- a/components/external/SQLite-3.8.1/tool/mkvsix.tcl +++ /dev/null @@ -1,655 +0,0 @@ -#!/usr/bin/tclsh -# -# This script is used to generate a VSIX (Visual Studio Extension) file for -# SQLite usable by Visual Studio. -# -# PREREQUISITES -# -# 1. Tcl 8.4 and later are supported, earlier versions have not been tested. -# -# 2. The "sqlite3.h" file is assumed to exist in the parent directory of the -# directory containing this script. The [optional] second command line -# argument to this script may be used to specify an alternate location. -# This script also assumes that the "sqlite3.h" file corresponds with the -# version of the binaries to be packaged. This assumption is not verified -# by this script. -# -# 3. The temporary directory specified in the TEMP or TMP environment variables -# must refer to an existing directory writable by the current user. -# -# 4. The "zip" and "unzip" command line tools must be located either in a -# directory contained in the PATH environment variable or specified as the -# exact file names to execute in the "ZipTool" and "UnZipTool" environment -# variables, respectively. -# -# 5. The template VSIX file (which is basically a zip file) must be located in -# a "win" directory inside the directory containing this script. It should -# not contain any executable binaries. It should only contain dynamic -# textual content files to be processed using [subst] and/or static content -# files to be copied verbatim. -# -# 6. The executable and other compiled binary files to be packaged into the -# final VSIX file (e.g. DLLs, LIBs, and PDBs) must be located in a single -# directory tree. The top-level directory of the tree must be specified as -# the first command line argument to this script. The second level -# sub-directory names must match those of the build configuration (e.g. -# "Debug" or "Retail"). The third level sub-directory names must match -# those of the platform (e.g. "x86", "x64", and "ARM"). For example, the -# binary files to be packaged would need to be organized as follows when -# packaging the "Debug" and "Retail" build configurations for the "x86" and -# "x64" platforms (in this example, "C:\temp" is the top-level directory as -# specified in the first command line argument): -# -# C:\Temp\Debug\x86\sqlite3.lib -# C:\Temp\Debug\x86\sqlite3.dll -# C:\Temp\Debug\x86\sqlite3.pdb -# C:\Temp\Debug\x64\sqlite3.lib -# C:\Temp\Debug\x64\sqlite3.dll -# C:\Temp\Debug\x64\sqlite3.pdb -# C:\Temp\Retail\x86\sqlite3.lib -# C:\Temp\Retail\x86\sqlite3.dll -# C:\Temp\Retail\x86\sqlite3.pdb -# C:\Temp\Retail\x64\sqlite3.lib -# C:\Temp\Retail\x64\sqlite3.dll -# C:\Temp\Retail\x64\sqlite3.pdb -# -# The above directory tree organization is performed automatically if the -# "tool\build-all-msvc.bat" batch script is used to build the binary files -# to be packaged. -# -# USAGE -# -# The first argument to this script is required and must be the name of the -# top-level directory containing the directories and files organized into a -# tree as described in item 6 of the PREREQUISITES section, above. The second -# argument is optional and if present must contain the name of the directory -# containing the root of the source tree for SQLite. The third argument is -# optional and if present must contain the flavor the VSIX package to build. -# Currently, the only supported package flavors are "WinRT", "WinRT81", and -# "WP80". The fourth argument is optional and if present must be a string -# containing a list of platforms to include in the VSIX package. The format -# of the platform list string is "platform1,platform2,platform3". Typically, -# when on Windows, this script is executed using commands similar to the -# following from a normal Windows command prompt: -# -# CD /D C:\dev\sqlite\core -# tclsh85 tool\mkvsix.tcl C:\Temp -# -# In the example above, "C:\dev\sqlite\core" represents the root of the source -# tree for SQLite and "C:\Temp" represents the top-level directory containing -# the executable and other compiled binary files, organized into a directory -# tree as described in item 6 of the PREREQUISITES section, above. -# -# This script should work on non-Windows platforms as well, provided that all -# the requirements listed in the PREREQUISITES section are met. -# -# NOTES -# -# The temporary directory is used as a staging area for the final VSIX file. -# The template VSIX file is extracted, its contents processed, and then the -# resulting files are packaged into the final VSIX file. -# -package require Tcl 8.4 - -proc fail { {error ""} {usage false} } { - if {[string length $error] > 0} then { - puts stdout $error - if {!$usage} then {exit 1} - } - - puts stdout "usage:\ -[file tail [info nameofexecutable]]\ -[file tail [info script]] \[sourceDirectory\]\ -\[packageFlavor\] \[platformNames\]" - - exit 1 -} - -proc getEnvironmentVariable { name } { - # - # NOTE: Returns the value of the specified environment variable or an empty - # string for environment variables that do not exist in the current - # process environment. - # - return [expr {[info exists ::env($name)] ? $::env($name) : ""}] -} - -proc getTemporaryPath {} { - # - # NOTE: Returns the normalized path to the first temporary directory found - # in the typical set of environment variables used for that purpose - # or an empty string to signal a failure to locate such a directory. - # - set names [list] - - foreach name [list TEMP TMP] { - lappend names [string toupper $name] [string tolower $name] \ - [string totitle $name] - } - - foreach name $names { - set value [getEnvironmentVariable $name] - - if {[string length $value] > 0} then { - return [file normalize $value] - } - } - - return "" -} - -proc appendArgs { args } { - # - # NOTE: Returns all passed arguments joined together as a single string with - # no intervening spaces between arguments. - # - eval append result $args -} - -proc readFile { fileName } { - # - # NOTE: Reads and returns the entire contents of the specified file, which - # may contain binary data. - # - set file_id [open $fileName RDONLY] - fconfigure $file_id -encoding binary -translation binary - set result [read $file_id] - close $file_id - return $result -} - -proc writeFile { fileName data } { - # - # NOTE: Writes the entire contents of the specified file, which may contain - # binary data. - # - set file_id [open $fileName {WRONLY CREAT TRUNC}] - fconfigure $file_id -encoding binary -translation binary - puts -nonewline $file_id $data - close $file_id - return "" -} - -proc substFile { fileName } { - # - # NOTE: Performs all Tcl command, variable, and backslash substitutions in - # the specified file and then rewrites the contents of that same file - # with the substituted data. - # - return [writeFile $fileName [uplevel 1 [list subst [readFile $fileName]]]] -} - -proc replaceFileNameTokens { fileName name buildName platformName } { - # - # NOTE: Returns the specified file name containing the platform name instead - # of platform placeholder tokens. - # - return [string map [list $buildName $platformName \ - $name] $fileName] -} - -# -# NOTE: This is the entry point for this script. -# -set script [file normalize [info script]] - -if {[string length $script] == 0} then { - fail "script file currently being evaluated is unknown" true -} - -set path [file dirname $script] -set rootName [file rootname [file tail $script]] - -############################################################################### - -# -# NOTE: Process and verify all the command line arguments. -# -set argc [llength $argv] -if {$argc < 1 || $argc > 4} then {fail} - -set binaryDirectory [lindex $argv 0] - -if {[string length $binaryDirectory] == 0} then { - fail "invalid binary directory" -} - -if {![file exists $binaryDirectory] || \ - ![file isdirectory $binaryDirectory]} then { - fail "binary directory does not exist" -} - -if {$argc >= 2} then { - set sourceDirectory [lindex $argv 1] -} else { - # - # NOTE: Assume that the source directory is the parent directory of the one - # that contains this script file. - # - set sourceDirectory [file dirname $path] -} - -if {[string length $sourceDirectory] == 0} then { - fail "invalid source directory" -} - -if {![file exists $sourceDirectory] || \ - ![file isdirectory $sourceDirectory]} then { - fail "source directory does not exist" -} - -if {$argc >= 3} then { - set packageFlavor [lindex $argv 2] -} else { - # - # NOTE: Assume the package flavor is WinRT. - # - set packageFlavor WinRT -} - -if {[string length $packageFlavor] == 0} then { - fail "invalid package flavor" -} - -if {[string equal -nocase $packageFlavor WinRT]} then { - set shortName SQLite.WinRT - set displayName "SQLite for Windows Runtime" - set targetPlatformIdentifier Windows - set targetPlatformVersion v8.0 - set minVsVersion 11.0 - set extraSdkPath "" - set extraFileListAttributes [appendArgs \ - "\r\n " {AppliesTo="WindowsAppContainer"} \ - "\r\n " {DependsOn="Microsoft.VCLibs, version=11.0"}] -} elseif {[string equal -nocase $packageFlavor WinRT81]} then { - set shortName SQLite.WinRT81 - set displayName "SQLite for Windows Runtime (Windows 8.1)" - set targetPlatformIdentifier Windows - set targetPlatformVersion v8.1 - set minVsVersion 12.0 - set extraSdkPath "" - set extraFileListAttributes [appendArgs \ - "\r\n " {AppliesTo="WindowsAppContainer"} \ - "\r\n " {DependsOn="Microsoft.VCLibs, version=12.0"}] -} elseif {[string equal -nocase $packageFlavor WP80]} then { - set shortName SQLite.WP80 - set displayName "SQLite for Windows Phone" - set targetPlatformIdentifier "Windows Phone" - set targetPlatformVersion v8.0 - set minVsVersion 11.0 - set extraSdkPath "\\..\\$targetPlatformIdentifier" - set extraFileListAttributes "" -} elseif {[string equal -nocase $packageFlavor Win32]} then { - set shortName SQLite.Win32 - set displayName "SQLite for Windows" - set targetPlatformIdentifier Windows - set targetPlatformVersion v8.0 - set minVsVersion 11.0 - set extraSdkPath "" - set extraFileListAttributes [appendArgs \ - "\r\n " {AppliesTo="VisualC"} \ - "\r\n " {DependsOn="Microsoft.VCLibs, version=11.0"}] -} else { - fail "unsupported package flavor, must be one of: WinRT WinRT81 WP80 Win32" -} - -if {$argc >= 4} then { - set platformNames [list] - - foreach platformName [split [lindex $argv 3] ", "] { - if {[string length $platformName] > 0} then { - lappend platformNames $platformName - } - } -} - -############################################################################### - -# -# NOTE: Evaluate the user-specific customizations file, if it exists. -# -set userFile [file join $path [appendArgs \ - $rootName . $tcl_platform(user) .tcl]] - -if {[file exists $userFile] && \ - [file isfile $userFile]} then { - source $userFile -} - -############################################################################### - -set templateFile [file join $path win sqlite.vsix] - -if {![file exists $templateFile] || \ - ![file isfile $templateFile]} then { - fail [appendArgs "template file \"" $templateFile "\" does not exist"] -} - -set currentDirectory [pwd] -set outputFile [file join $currentDirectory [appendArgs sqlite- \ - $packageFlavor -output.vsix]] - -if {[file exists $outputFile]} then { - fail [appendArgs "output file \"" $outputFile "\" already exists"] -} - -############################################################################### - -# -# NOTE: Make sure that a valid temporary directory exists. -# -set temporaryDirectory [getTemporaryPath] - -if {[string length $temporaryDirectory] == 0 || \ - ![file exists $temporaryDirectory] || \ - ![file isdirectory $temporaryDirectory]} then { - fail "cannot locate a usable temporary directory" -} - -# -# NOTE: Setup the staging directory to have a unique name inside of the -# configured temporary directory. -# -set stagingDirectory [file normalize [file join $temporaryDirectory \ - [appendArgs $rootName . [pid]]]] - -############################################################################### - -# -# NOTE: Configure the external zipping tool. First, see if it has already -# been pre-configured. If not, try to query it from the environment. -# Finally, fallback on the default of simply "zip", which will then -# be assumed to exist somewhere along the PATH. -# -if {![info exists zip]} then { - if {[info exists env(ZipTool)]} then { - set zip $env(ZipTool) - } - if {![info exists zip] || ![file exists $zip]} then { - set zip zip - } -} - -# -# NOTE: Configure the external unzipping tool. First, see if it has already -# been pre-configured. If not, try to query it from the environment. -# Finally, fallback on the default of simply "unzip", which will then -# be assumed to exist somewhere along the PATH. -# -if {![info exists unzip]} then { - if {[info exists env(UnZipTool)]} then { - set unzip $env(UnZipTool) - } - if {![info exists unzip] || ![file exists $unzip]} then { - set unzip unzip - } -} - -############################################################################### - -# -# NOTE: Attempt to extract the SQLite version from the "sqlite3.h" header file -# in the source directory. This script assumes that the header file has -# already been generated by the build process. -# -set pattern {^#define\s+SQLITE_VERSION\s+"(.*)"$} -set data [readFile [file join $sourceDirectory sqlite3.h]] - -if {![regexp -line -- $pattern $data dummy version]} then { - fail [appendArgs "cannot locate SQLITE_VERSION value in \"" \ - [file join $sourceDirectory sqlite3.h] \"] -} - -############################################################################### - -# -# NOTE: Setup all the master file list data. This includes the source file -# names, the destination file names, and the file processing flags. The -# possible file processing flags are: -# -# "buildNeutral" -- This flag indicates the file location and content do -# not depend on the build configuration. -# -# "platformNeutral" -- This flag indicates the file location and content -# do not depend on the build platform. -# -# "subst" -- This flag indicates that the file contains dynamic textual -# content that needs to be processed using [subst] prior to -# packaging the file into the final VSIX package. The primary -# use of this flag is to insert the name of the VSIX package, -# some package flavor-specific value, or the SQLite version -# into a file. -# -# "noDebug" -- This flag indicates that the file should be skipped when -# processing the debug build. -# -# "noRetail" -- This flag indicates that the file should be skipped when -# processing the retail build. -# -# "move" -- This flag indicates that the file should be moved from the -# source to the destination instead of being copied. -# -# This file metadata may be overridden, either in whole or in part, via -# the user-specific customizations file. -# -if {![info exists fileNames(source)]} then { - set fileNames(source) [list "" "" \ - [file join $stagingDirectory DesignTime sqlite3.props] \ - [file join $sourceDirectory sqlite3.h] \ - [file join $binaryDirectory sqlite3.lib] \ - [file join $binaryDirectory sqlite3.dll]] - - if {![info exists no(symbols)]} then { - lappend fileNames(source) \ - [file join $binaryDirectory sqlite3.pdb] - } -} - -if {![info exists fileNames(destination)]} then { - set fileNames(destination) [list \ - [file join $stagingDirectory extension.vsixmanifest] \ - [file join $stagingDirectory SDKManifest.xml] \ - [file join $stagingDirectory DesignTime .props] \ - [file join $stagingDirectory DesignTime sqlite3.h] \ - [file join $stagingDirectory DesignTime sqlite3.lib] \ - [file join $stagingDirectory Redist sqlite3.dll]] - - if {![info exists no(symbols)]} then { - lappend fileNames(destination) \ - [file join $stagingDirectory Redist sqlite3.pdb] - } -} - -if {![info exists fileNames(flags)]} then { - set fileNames(flags) [list \ - [list buildNeutral platformNeutral subst] \ - [list buildNeutral platformNeutral subst] \ - [list buildNeutral platformNeutral subst move] \ - [list buildNeutral platformNeutral] \ - [list] [list] [list noRetail]] - - if {![info exists no(symbols)]} then { - lappend fileNames(flags) [list noRetail] - } -} - -############################################################################### - -# -# NOTE: Setup the list of builds supported by this script. These may be -# overridden via the user-specific customizations file. -# -if {![info exists buildNames]} then { - set buildNames [list Debug Retail] -} - -############################################################################### - -# -# NOTE: Setup the list of platforms supported by this script. These may be -# overridden via the command line or the user-specific customizations -# file. -# -if {![info exists platformNames]} then { - set platformNames [list x86 x64 ARM] -} - -############################################################################### - -# -# NOTE: Make sure the staging directory exists, creating it if necessary. -# -file mkdir $stagingDirectory - -# -# NOTE: Build the Tcl command used to extract the template VSIX package to -# the staging directory. -# -set extractCommand [list exec -- $unzip $templateFile -d $stagingDirectory] - -# -# NOTE: Extract the template VSIX package to the staging directory. -# -eval $extractCommand - -############################################################################### - -# -# NOTE: Process each file in the master file list. There are actually three -# parallel lists that contain the source file names, the destination file -# names, and the file processing flags. If the "buildNeutral" flag is -# present, the file location and content do not depend on the build -# configuration and "CommonConfiguration" will be used in place of the -# build configuration name. If the "platformNeutral" flag is present, -# the file location and content do not depend on the build platform and -# "neutral" will be used in place of the build platform name. If the -# "subst" flag is present, the file is assumed to be a text file that may -# contain Tcl variable, command, and backslash replacements, to be -# dynamically replaced during processing using the Tcl [subst] command. -# If the "noDebug" flag is present, the file will be skipped when -# processing for the debug build. If the "noRetail" flag is present, the -# file will be skipped when processing for the retail build. If the -# "move" flag is present, the source file will be deleted after it is -# copied to the destination file. If the source file name is an empty -# string, the destination file name will be assumed to already exist in -# the staging directory and will not be copied; however, Tcl variable, -# command, and backslash replacements may still be performed on the -# destination file prior to the final VSIX package being built if the -# "subst" flag is present. -# -foreach sourceFileName $fileNames(source) \ - destinationFileName $fileNames(destination) \ - fileFlags $fileNames(flags) { - # - # NOTE: Process the file flags into separate boolean variables that may be - # used within the loop. - # - set isBuildNeutral [expr {[lsearch $fileFlags buildNeutral] != -1}] - set isPlatformNeutral [expr {[lsearch $fileFlags platformNeutral] != -1}] - set isMove [expr {[lsearch $fileFlags move] != -1}] - set useSubst [expr {[lsearch $fileFlags subst] != -1}] - - # - # NOTE: If the current file is build-neutral, then only one build will - # be processed for it, namely "CommonConfiguration"; otherwise, each - # supported build will be processed for it individually. - # - foreach buildName \ - [expr {$isBuildNeutral ? [list CommonConfiguration] : $buildNames}] { - # - # NOTE: Should the current file be skipped for this build? - # - if {[lsearch $fileFlags no${buildName}] != -1} then { - continue - } - - # - # NOTE: If the current file is platform-neutral, then only one platform - # will be processed for it, namely "neutral"; otherwise, each - # supported platform will be processed for it individually. - # - foreach platformName \ - [expr {$isPlatformNeutral ? [list neutral] : $platformNames}] { - # - # NOTE: Use the actual platform name in the destination file name. - # - set newDestinationFileName [replaceFileNameTokens $destinationFileName \ - $shortName $buildName $platformName] - - # - # NOTE: Does the source file need to be copied to the destination file? - # - if {[string length $sourceFileName] > 0} then { - # - # NOTE: First, make sure the destination directory exists. - # - file mkdir [file dirname $newDestinationFileName] - - # - # NOTE: Then, copy the source file to the destination file verbatim. - # - set newSourceFileName [replaceFileNameTokens $sourceFileName \ - $shortName $buildName $platformName] - - file copy $newSourceFileName $newDestinationFileName - - # - # NOTE: If this is a move instead of a copy, delete the source file - # now. - # - if {$isMove} then { - file delete $newSourceFileName - } - } - - # - # NOTE: Does the destination file contain dynamic replacements that must - # be processed now? - # - if {$useSubst} then { - # - # NOTE: Perform any dynamic replacements contained in the destination - # file and then re-write it in-place. - # - substFile $newDestinationFileName - } - } - } -} - -############################################################################### - -# -# NOTE: Change the current directory to the staging directory so that the -# external archive building tool can pickup the necessary files using -# relative paths. -# -cd $stagingDirectory - -# -# NOTE: Build the Tcl command used to archive the final VSIX package in the -# output directory. -# -set archiveCommand [list exec -- $zip -r $outputFile *] - -# -# NOTE: Build the final VSIX package archive in the output directory. -# -eval $archiveCommand - -# -# NOTE: Change back to the previously saved current directory. -# -cd $currentDirectory - -# -# NOTE: Cleanup the temporary staging directory. -# -file delete -force $stagingDirectory - -############################################################################### - -# -# NOTE: Success, emit the fully qualified path of the generated VSIX file. -# -puts stdout $outputFile diff --git a/components/external/SQLite-3.8.1/tool/offsets.c b/components/external/SQLite-3.8.1/tool/offsets.c deleted file mode 100644 index 8e098e71cb..0000000000 --- a/components/external/SQLite-3.8.1/tool/offsets.c +++ /dev/null @@ -1,329 +0,0 @@ -/* -** This program searches an SQLite database file for the lengths and -** offsets for all TEXT or BLOB entries for a particular column of a -** particular table. The rowid, size and offset for the column are -** written to standard output. There are three arguments, which are the -** name of the database file, the table, and the column. -*/ -#include "sqlite3.h" -#include -#include -#include -#include - -typedef unsigned char u8; -typedef struct GState GState; - -#define ArraySize(X) (sizeof(X)/sizeof(X[0])) - -/* -** Global state information for this program. -*/ -struct GState { - char *zErr; /* Error message text */ - FILE *f; /* Open database file */ - int szPg; /* Page size for the database file */ - int iRoot; /* Root page of the table */ - int iCol; /* Column number for the column */ - int pgno; /* Current page number */ - u8 *aPage; /* Current page content */ - u8 *aStack[20]; /* Page stack */ - int aPgno[20]; /* Page number stack */ - int nStack; /* Depth of stack */ - int bTrace; /* True for tracing output */ -}; - -/* -** Write an error. -*/ -static void ofstError(GState *p, const char *zFormat, ...){ - va_list ap; - sqlite3_free(p->zErr); - va_start(ap, zFormat); - p->zErr = sqlite3_vmprintf(zFormat, ap); - va_end(ap); -} - -/* -** Write a trace message -*/ -static void ofstTrace(GState *p, const char *zFormat, ...){ - va_list ap; - if( p->bTrace ){ - va_start(ap, zFormat); - vprintf(zFormat, ap); - va_end(ap); - } -} - -/* -** Find the root page of the table and the column number of the column. -*/ -static void ofstRootAndColumn( - GState *p, /* Global state */ - const char *zFile, /* Name of the database file */ - const char *zTable, /* Name of the table */ - const char *zColumn /* Name of the column */ -){ - sqlite3 *db = 0; - sqlite3_stmt *pStmt = 0; - char *zSql = 0; - int rc; - if( p->zErr ) return; - rc = sqlite3_open(zFile, &db); - if( rc ){ - ofstError(p, "cannot open database file \"%s\"", zFile); - goto rootAndColumn_exit; - } - zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master WHERE name=%Q", - zTable); - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - if( rc ) ofstError(p, "%s: [%s]", sqlite3_errmsg(db), zSql); - sqlite3_free(zSql); - if( p->zErr ) goto rootAndColumn_exit; - if( sqlite3_step(pStmt)!=SQLITE_ROW ){ - ofstError(p, "cannot find table [%s]\n", zTable); - sqlite3_finalize(pStmt); - goto rootAndColumn_exit; - } - p->iRoot = sqlite3_column_int(pStmt , 0); - sqlite3_finalize(pStmt); - - p->iCol = -1; - zSql = sqlite3_mprintf("PRAGMA table_info(%Q)", zTable); - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - if( rc ) ofstError(p, "%s: [%s}", sqlite3_errmsg(db), zSql); - sqlite3_free(zSql); - if( p->zErr ) goto rootAndColumn_exit; - while( sqlite3_step(pStmt)==SQLITE_ROW ){ - const char *zCol = sqlite3_column_text(pStmt, 1); - if( strlen(zCol)==strlen(zColumn) - && sqlite3_strnicmp(zCol, zColumn, strlen(zCol))==0 - ){ - p->iCol = sqlite3_column_int(pStmt, 0); - break; - } - } - sqlite3_finalize(pStmt); - if( p->iCol<0 ){ - ofstError(p, "no such column: %s.%s", zTable, zColumn); - goto rootAndColumn_exit; - } - - zSql = sqlite3_mprintf("PRAGMA page_size"); - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - if( rc ) ofstError(p, "%s: [%s]", sqlite3_errmsg(db), zSql); - sqlite3_free(zSql); - if( p->zErr ) goto rootAndColumn_exit; - if( sqlite3_step(pStmt)!=SQLITE_ROW ){ - ofstError(p, "cannot find page size"); - }else{ - p->szPg = sqlite3_column_int(pStmt, 0); - } - sqlite3_finalize(pStmt); - -rootAndColumn_exit: - sqlite3_close(db); - return; -} - -/* -** Pop a page from the stack -*/ -static void ofstPopPage(GState *p){ - if( p->nStack<=0 ) return; - p->nStack--; - sqlite3_free(p->aStack[p->nStack]); - p->pgno = p->aPgno[p->nStack-1]; - p->aPage = p->aStack[p->nStack-1]; -} - - -/* -** Push a new page onto the stack. -*/ -static void ofstPushPage(GState *p, int pgno){ - u8 *pPage; - size_t got; - if( p->zErr ) return; - if( p->nStack >= ArraySize(p->aStack) ){ - ofstError(p, "page stack overflow"); - return; - } - p->aPgno[p->nStack] = pgno; - p->aStack[p->nStack] = pPage = sqlite3_malloc( p->szPg ); - if( pPage==0 ){ - fprintf(stderr, "out of memory\n"); - exit(1); - } - p->nStack++; - p->aPage = pPage; - p->pgno = pgno; - fseek(p->f, (pgno-1)*p->szPg, SEEK_SET); - got = fread(pPage, 1, p->szPg, p->f); - if( got!=p->szPg ){ - ofstError(p, "unable to read page %d", pgno); - ofstPopPage(p); - } -} - -/* Read a two-byte integer at the given offset into the current page */ -static int ofst2byte(GState *p, int ofst){ - int x = p->aPage[ofst]; - return (x<<8) + p->aPage[ofst+1]; -} - -/* Read a four-byte integer at the given offset into the current page */ -static int ofst4byte(GState *p, int ofst){ - int x = p->aPage[ofst]; - x = (x<<8) + p->aPage[ofst+1]; - x = (x<<8) + p->aPage[ofst+2]; - x = (x<<8) + p->aPage[ofst+3]; - return x; -} - -/* Read a variable-length integer. Update the offset */ -static sqlite3_int64 ofstVarint(GState *p, int *pOfst){ - sqlite3_int64 x = 0; - u8 *a = &p->aPage[*pOfst]; - int n = 0; - while( n<8 && (a[0] & 0x80)!=0 ){ - x = (x<<7) + (a[0] & 0x7f); - n++; - a++; - } - if( n==8 ){ - x = (x<<8) + a[0]; - }else{ - x = (x<<7) + a[0]; - } - *pOfst += (n+1); - return x; -} - -/* Return the absolute offset into a file for the given offset -** into the current page */ -static int ofstInFile(GState *p, int ofst){ - return p->szPg*(p->pgno-1) + ofst; -} - -/* Return the size (in bytes) of the data corresponding to the -** given serial code */ -static int ofstSerialSize(int scode){ - if( scode<5 ) return scode; - if( scode==5 ) return 6; - if( scode<8 ) return 8; - if( scode<12 ) return 0; - return (scode-12)/2; -} - -/* Forward reference */ -static void ofstWalkPage(GState*, int); - -/* Walk an interior btree page */ -static void ofstWalkInteriorPage(GState *p){ - int nCell; - int i; - int ofst; - int iChild; - - nCell = ofst2byte(p, 3); - for(i=0; izErr ) return; - } - ofstWalkPage(p, ofst4byte(p, 8)); -} - -/* Walk a leaf btree page */ -static void ofstWalkLeafPage(GState *p){ - int nCell; - int i; - int ofst; - int nPayload; - sqlite3_int64 rowid; - int nHdr; - int j; - int scode; - int sz; - int dataOfst; - char zMsg[200]; - - nCell = ofst2byte(p, 3); - for(i=0; i p->szPg-35 ){ - sqlite3_snprintf(sizeof(zMsg), zMsg, - "# overflow rowid %lld", rowid); - printf("%s\n", zMsg); - continue; - } - dataOfst = ofst; - nHdr = ofstVarint(p, &ofst); - dataOfst += nHdr; - for(j=0; jiCol; j++){ - scode = ofstVarint(p, &ofst); - dataOfst += ofstSerialSize(scode); - } - scode = ofstVarint(p, &ofst); - sz = ofstSerialSize(scode); - sqlite3_snprintf(sizeof(zMsg), zMsg, - "rowid %12lld size %5d offset %8d", - rowid, sz, ofstInFile(p, dataOfst)); - printf("%s\n", zMsg); - } -} - -/* -** Output results from a single page. -*/ -static void ofstWalkPage(GState *p, int pgno){ - if( p->zErr ) return; - ofstPushPage(p, pgno); - if( p->zErr ) return; - if( p->aPage[0]==5 ){ - ofstWalkInteriorPage(p); - }else if( p->aPage[0]==13 ){ - ofstWalkLeafPage(p); - }else{ - ofstError(p, "page %d has a faulty type byte: %d", pgno, p->aPage[0]); - } - ofstPopPage(p); -} - -int main(int argc, char **argv){ - GState g; - memset(&g, 0, sizeof(g)); - if( argc>2 && strcmp(argv[1],"--trace")==0 ){ - g.bTrace = 1; - argc--; - argv++; - } - if( argc!=4 ){ - fprintf(stderr, "Usage: %s DATABASE TABLE COLUMN\n", *argv); - exit(1); - } - ofstRootAndColumn(&g, argv[1], argv[2], argv[3]); - if( g.zErr ){ - fprintf(stderr, "%s\n", g.zErr); - exit(1); - } - ofstTrace(&g, "# szPg = %d\n", g.szPg); - ofstTrace(&g, "# iRoot = %d\n", g.iRoot); - ofstTrace(&g, "# iCol = %d\n", g.iCol); - g.f = fopen(argv[1], "rb"); - if( g.f==0 ){ - fprintf(stderr, "cannot open \"%s\"\n", argv[1]); - exit(1); - } - ofstWalkPage(&g, g.iRoot); - if( g.zErr ){ - fprintf(stderr, "%s\n", g.zErr); - exit(1); - } - return 0; -} diff --git a/components/external/SQLite-3.8.1/tool/omittest.tcl b/components/external/SQLite-3.8.1/tool/omittest.tcl deleted file mode 100644 index 3351b96b32..0000000000 --- a/components/external/SQLite-3.8.1/tool/omittest.tcl +++ /dev/null @@ -1,298 +0,0 @@ - -set rcsid {$Id: omittest.tcl,v 1.8 2008/10/13 15:35:09 drh Exp $} - -# Documentation for this script. This may be output to stderr -# if the script is invoked incorrectly. -set ::USAGE_MESSAGE { -This Tcl script is used to test the various compile time options -available for omitting code (the SQLITE_OMIT_xxx options). It -should be invoked as follows: - -